DEV Community

Edwin Torres
Edwin Torres

Posted on

Tutorial: Write Your First JavaScript Program

JavaScript programs execute in the browser. That means you need an HTML document. Here is a simple one to start with:

<!DOCTYPE html>
<html lang="en">
<head>
<title>My document</title>
</head>
<body>


</body>
</html>
Enter fullscreen mode Exit fullscreen mode

That is a very basic HTML document that doesn’t do much. For now, save it to a file named helloworld.html. The .html extension indicates that the file is an HTML document.

Now add JavaScript to the HTML document. Write JavaScript code inside a <script> </script> element:

<!DOCTYPE html>
<html lang="en">
<head>
<title>My document</title>
</head>
<body>

<script>
let s = "Hello, world.";

document.write(s);

console.log(s);
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This JavaScript code declares a variable s and assigns the string "Hello, world." to it.

Next, it outputs s to the document.

Finally, it outputs s to the console.

To execute the JavaScript code, double-click the helloworld.html file. The program will execute in your browser. Note the output in the body of the document.

To see the console output, view the browser console:

  • Right-click anywhere in the document and click Inspect.
  • Expand the browser window wide.
  • Click the Console tab in the top-right.

🏆 Congratulations! That’s your first JavaScript program!

Now you can explore and learn the rest of the JavaScript language.

Follow me on Twitter @realEdwinTorres for more programming tips. 😀

Top comments (0)