1.3 JavaScript in Browsers

We are now ready to write our first JavaScript code. To run JavaScript inside an HTML page, you need a <script> element. There are two places where you can add it: inside the <head> tag, or inside the <body> tag. The best practice is to place the script element at the end of the body, just after your visible elements such as <h1> and <p>.

Why place the script at the end of body?

There are two main reasons to follow this convention:

  • The browser parses HTML from top to bottom. If the script sits in the head, the browser is busy executing JavaScript instead of rendering the content, which creates a poor user experience.
  • The code inside the script often needs to interact with the page elements — for example to show or hide some of them. Placing the script last guarantees that all these elements have already been rendered.

Now let's write a small piece of JavaScript. Inside the script element, type console.log("Hello everyone");. What you see here is a statement: an instruction that expresses an action to perform. Every JavaScript statement should end with a semicolon. The text between the quotes is called a string of characters. This little message will be sent directly to the browser console.

You can also document your code with comments. A comment starts with // and is ignored by the JavaScript engine — it only exists for the developer. After saving the file and refreshing the browser, open the developer console: you will see "Hello everyone" printed there. That's it for this video, see you in the next one!