Skip to main content

JavaScript Basics

Script tag

You can insert JavaScript program into HTML document using the <script> tags.

You can write inline scripts directly between the tags or you can include external scripts. In order to include external script you would specify the src attribute for the script tag.

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

If the src attribute is set, the script content is ignored.

Code Structure

Statement

Code in JavaScript can be ended with semicolons, or without semicolons if the statements are on line break

alert("Hello World");
alert("This is hello!");

or

alert("Hello World")
alert("This is hello!")

Having semicolons for the end of a statement is good practice because the JavaScript might do wrong assumption of when to actually insert or not insert the semicolon take a look at the example below:

alert("Hello");

[1, 2].forEach(alert);

// The two statement above will print out "Hello" then 1 and 2, which is what we expected

The two statement above will print out "Hello" then 1 and 2, which is what we expected.

However, if we change up the code to be the following:

alert("Hello")

[1, 2].forEach(alert);

The code will only print out "Hello", and then it will display an error. This is because JavaScript doesn't insert semicolon before square brackets, therefore the two lines are treated as if they are one line

alert("Hello")[1, 2].forEach(alert);
Comments
// This is a comment

/* This is a multi-line
comment :).
*/

Not nesting /* */ comments just lie in C.