Hello World

Lesson 3
Author : Afrixi
Last Updated : March, 2023
Javascript - Program the Web
This course covers the basics of programming in Javascript.

To get started, we need a working environment to run our JavaScript code, and since this course is online, we’ll be using the browser as our environment. We’ll keep the use of browser-specific commands, such as alert, to a minimum so that you can focus on the language fundamentals.

To attach a JavaScript script to an HTML document, we use the <script> tag. Here’s an example:


<!DOCTYPE HTML>
<html>
  <body>
    <p>Before the script...</p>
    <script>
      alert( 'Hello, world!' );
    </script>
    <p>...After the script.</p>
  </body>
</html>

When the browser processes the <script> tag, the JavaScript code contained within it is automatically executed.

The <script> tag has two attributes, type and language, which are rarely used nowadays. type was required in the old HTML standard (HTML4) and usually set to “text/javascript”, but it’s not required anymore. language was meant to show the language of the script, but it’s no longer necessary since JavaScript is the default language.

If you have a lot of JavaScript code, it’s a good practice to put it in a separate file and attach it to the HTML document using the src attribute of the <script> tag. Here’s an example:

<script src="/path/to/script.js"></script>

The src attribute takes a path to the script file, either absolute or relative to the current page.

One benefit of using a separate file is that the browser can download it and store it in its cache. Other pages that reference the same script will take it from the cache instead of downloading it again, which makes the pages load faster and reduces traffic.

It’s important to note that a single <script> tag can’t have both the src attribute and code inside. If you need to use both, you’ll need to split it into two <script> tags.

That’s it for this part of the tutorial! We hope this introduction to attaching JavaScript to an HTML document has been helpful. In the next part, we’ll dive deeper into the language fundamentals.