Getting started with JavaScript

Coding with JavaScript

🕑 This lesson will take about 10 minutes

This is the first lesson on JavaScript in this series. In this lesson, you will learn how to set up an HTML document (web page) to use JavaScript code and how to display a message in the web browser using JavaScript. You will also learn how to write the code in a suitable text editor program and how to test your code using the JavaScript console in Google Chrome and other browsers.

You will need a code editor to write your code. Some suggested code editors are:

It will be best to have at least a basic knowledge of HTML and CSS so if you don’t, then please check out the Web Design with HTML & CSS course and then come back here to start learning JavaScript.

Watch the video below for an introduction to JavaScript coding and then scroll down for the example code.

The example code below can be copied to an HTML file (a file ending in .html). The HTML code contains some JavaScript code which will basically display a “Hello world” message in the browser window and the browser console (in Chrome, right-click the page and then click Inspect to access developer tools, then click the Console tab). The console can be used to display messages during testing and also to view any error messages if there are problems with your code.

The code also shows an example of placing JavaScript code in a separate JS file and examples of using single-line and multi-line comments to add notes to your code. Simply copy and paste the code snippet into a text editor and save the file as yourfilename.html . Then open this file in your preferred browser to run the code.

Example code (HTML and JavaScript code in one file)

Example of an HTML file called index.html containing both HTML and JavaScript code in the one file (note that you may not see what is displayed in the console in the Codepen snippet below - click Edit on Codepen to in a new window or tab and then click Console at the bottom of the screen):

Example code (HTML and JavaScript code in separate files)

In the example below, the index.html links to a separate JavaScript (.js) file containing the JavaScript code. The HTML file only contains HTML code.

The <script src=”script.js”</script> tag is used to link the HTML document to a separate JavaScript file called script.js which contains all the JavaScript code. This is a better way of organising your code rather than mixing both HTML and JavaScript code in a single file.

In the Codepen snippet below, click the HTML tab to see the HTML code, and the JS tab to see the JavaScript code.