Engineer bro!

Sat Apr 09 2022 (6 months ago)

Engineer by mistake!

I am a software engineer by passion

Semicolon in JavaScript

Semicolons are an essential part of JavaScript code. They are read and used by the compiler to distinguish between separate statements so that statements do not leak into other parts of the code. The good feature is that JavaScript includes an automatic semicolon feature.

Statements in any programming language act like a command that performss some action. Every statement should be written on a new line, even a very long single statement can be written on multiple lines.

We can have as many statements as we want in a line.

console.log('Hello'); console.log('World');

Usually, the statements are separated with semicolons (;). The above statement can be written on multiple lines for more readability

console.log('Hello'); 
console.log('World');

Semicolon is not required in JavaScript, but it makes the code more readable.
JavaScript interprets the line break as an “implicit” semicolon.

automatic-semicolon-insertion

automatic-semicolon-insertion

automatic-semicolon-insertion

JavaScript automatically inserts a semicolon at the end of the statement, for more information that how it does it, you can read automatic-semicolon-insertion.

Sometimes this feature can create bugs in our application. Suppose you are reading some value of the array.

const item = [1,2,3]
[1]

console.log(item)

The above code will be interpreted as

const item = [1,2,3][1];
console.log(item);

There is not an issue, it's working fine. Now, let's have a look at the below code.

console.log("Hello");
[1,2].forEach(i=>console.log(i));

// output
Hello
1
2

Now try the below snippet

console.log("Hello")
[1,2].forEach(i=>console.log(i))

You'll get an error something like

Uncaught TypeError: Cannot read properties of undefined (reading '2')
    at <anonymous>:2:1

The reason of this is that, JavaScript does not insert semicolons before []. So, the above code was being treated like below by VM.

console.log("Hello")[1,2].forEach(i=>console.log(i))

Looks weird, right? Such merging in this case is just wrong. We need to put a semicolon after logging in for the code to work correctly.

This can happen in other situations also, so you should always insert a semicolon at the end of every statement.

Another example where it breaks without semicolon

// define a function
var fn = function () {
    //...
} // semicolon missing at this line

// then execute some code inside a closure
(function () {
    //...
})();

The above code will be interpreted as

var fn = function () {
    //...
}(function () {
    //...
})();
EngineeringSoftware EngineeringJavaScript

Comments (0)

Discussions (0)


© 2021 dsabyte. All rights reserved