Open In App

Semicolon in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

Semicolon in every language is very important for the compiler to understand the code. It denotes the end of the line in these languages but in the case of JavaScript, it is not necessary to add a semicolon to each line. It always remains the topic of debate whether one should use semicolons in each line of code of JavaScript or not. While it is true that I can save some bytes of memory by not using semicolons everywhere in the code, it is also true that using semicolons prevents facing any unwanted errors in compile time.

If you want to avoid using semicolons in your code then you must know about the rules that the compiler uses while adding the semicolon itself during the parsing of code.

The compiler adds the semicolon itself:

  • When the starting code in the next line breaks the code of the current line.
  • When the next line closes the current block by using ‘}’.
  • When there is a return statement on its line.
  • When there is a break statement on its line. 
  • When there is a throw statement on its line.
  • When there is a continue statement on its line.

Example: Below is an example of how to use semicolon.

Javascript




let a = 21;
let b = 31;
if (a < b) {
    console.log("a is less than b");
}
for (let i = 0; i < 10; i++) {
    if (i == 1)
        continue;
    else if (i == 5)
        break;
    else
        console.log(i);
}


Output

a is less than b
0
2
3
4

Example: In this example, both give the same result.

Javascript




// Both code works the same
console.log("Hello")
console.log("Hello");


Output

Hello
Hello

Example: But there are some cases where JS fails to add semicolons on required places which eventually causes syntax errors. Some of the examples are as follows:

Javascript




const Hey = 'hey'
const namaste = 'namaste'
const heyNamaste = Hey + ' ' + namaste
['h', 'e', 'y'].forEach((char) => console.log(char))



Error

So in this case according to rule 1 the starting code in last line doesn’t break the code of the previous line hence JS won’t add semicolon (;) in that line which eventually will cause an error.

Example: So the above code will be interpreted by JS as

Javascript




const Hey = 'hey';
const namaste = 'namaste';
const heyNamaste = Hey + ' '
    + namaste['h', 'e', 'y'].forEach((char) => console.log(char))


Conclusion: So in conclusion if you want to avoid facing such errors then you should use semicolons every time but since JS gives the privilege to avoid using them all the time one should be aware of the rules it uses to add semicolon so that any unwanted error can be avoided.



Last Updated : 08 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads