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.
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 own line.
- When there is a break statement on its own line.
- When there is a throw statement on its own line.
- When there is a continue statement on its own line.
Example: Now let’s understand this with some examples:
Javascript
<script> 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) } </script> |
Now this whole code will be interpreted by JS compiler as
Example:
Javascript
<script> 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); } </script> |
a is less than b 0 2 3 4
Another example is:
Javascript
<script> // Both code works the same console.log( "Hello" ) console.log( "Hello" ); </script> |
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
<script> const Hey = 'hey' const namaste = 'namaste' const heyNamaste = Hey + ' ' + namaste [ 'h' , 'e' , 'y' ].forEach((char) => console.log(char)) </script> |
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
<script> const Hey = 'hey' ; const namaste = 'namaste' ; const heyNamaste = Hey + ' ' + namaste[ 'h' , 'e' , 'y' ].forEach((char) => console.log(char)) </script> |
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.