JavaScript Code Structure

The first thing to learn in JavaScript is building blocks of JavaScript.

Semicolon

Semicolons in JavaScript are optional but they should not be ignored. They have a very important role in the script ( JavaScript Program ).
Normally, each JavaScript statement is separated by a semicolon. But the new line can also act as separator but not every time.


// Semicolon as a seperator
console.log("This is first statement"); console.log("This is second statement");
                    

As per the above code, if you want to write two statements in a single line, then you must add a semicolon between them. Otherwise, it will give an error.


// new line as a seperator
console.log("This is first statement")
console.log("This is second statement")
                    

If each statement is written in a new line, then you can ignore the semicolon. In this case, a new line character is acting as a separator.


// newline not working as a separater
console.log( 2 + 
3 + 
4)
                    

In the above case, a newline doesn't work as a separator, because JavaScript doesn't encounter a single statement. So when it encouters whole statement ( which is complete three lines), it considers one statement and executes it.

Sometimes JavaScript fails to find one complete statement if it is written in multiple lines. So it is advisable to write a single statement in one line and use a semicolon as a separator.

Comments

As time goes on and the project becomes big, programs become complex. So it is necessary to include comments in your programs so that you can understand and other programmers can understand the particular program or function. There are two types of comments in JavaScript.

One line comment

One line comment is two forward-slashes. : //


// This is single line comment.
console.log("This is first statement");
                    

Multi line comment

Multi line comments start with /* and ends with */.


/* This is multi line comment.
This is second line */
console.log("This is second statement");
                    

Conclusion

In this section, you learn about separator. And about comments and why you should use it.
In next section, you will learn about variables in JavaScript.