First JavaScript Program

Let’s create our first JavaScript program. To write and test JavaScript programs, we need two things: a test editor and a web browser.

As a text editor, you can take any that you like – Atom, Sublime Text, Visual Studio Code, Notepad ++ and others. In this tutorial, I will focus on the Visual Studio Code text editor , as it is the most popular.

You can also use the latest versions of any preferred web browser as the browser. In this guide, I will primarily focus on Google Chrome.

First, let’s define a directory for our application. For example, let’s create a folder app on drive C. In this folder, let’s create a file called index.html . That is, this file will represent a web page with HTML code.

Let’s open this file in a text editor and define the following code in the file:

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        document.write("<h2>The first program for JavaScript</h2>");


This is where we define standard html elements. The head element defines the utf-8 encoding and the title (element title). The body element defines the body of the web page, which in this case consists of only one <script> element.

The JavaScript code is connected to the html page using the <script> tag . This tag should be placed either in the header (between the <head>and tags </head>) or in the body of the web page (between the <body> and tags </body>). Often, scripts are included before the closing tag </body>to optimize the loading of the web page.

Previously, it was necessary to <script>specify the script type in the tag, since this tag can be used not only to connect JavaScript instructions, but also for other purposes. So, even now, you can see this definition of the script element on some web pages:

However, it is currently preferable to omit the type attribute, as browsers by default assume that the script element contains JavaScript instructions.

The javascript code we are using contains a single statement:

JavaScript code can contain many statements and each statement ends with a semicolon. Our statement calls the document.write() method , which writes some content to the web page, in this case the title <h2>The first program for JavaScript</h2>


View of the file in the Visual Studio Code text editor:

Now that the web page is ready, let’s open it in a web browser:

And the web browser will display the title that we have passed to the method document.write() in the javascript code.