Forming statements with semicolons

When we place one expression after another, we tend to terminate each individual one with a semicolon. By doing this, we are forming a statement. Explicitly terminating a statement ensures that the JavaScript parser will not have to do so automatically. If you don't use semicolons, then the parser will guess where to insert them via a process called ASI. This process relies on our placement of new lines (that is,  ).

As ASI is automatic, it won't always provide the outcomes you desire. For example, consider the following case where there is a function expression followed by a syntax that is intended as a group (that is, an expression delimited by parentheses):

(function() {})
(
[1, 2, 3]
).join(' ')

This will cause a mysterious TypeError that says: Cannot read property join of undefined. This is because, from the parser's point of view, the following is what we're doing:

(function() {})([1, 2, 3]).join(' ')

Here, we're creating an inline anonymous function and then immediately calling it, passing the [1, 2, 3] array as our sole argument, and then we're attempting to invoke the join method on whatever's returned. But as our function returns undefined, there is no join method there, and so we receive an error. This is a rare situation, but variations of this issue do crop up from time to time. The best way to avoid them is to consistently use semicolons to terminate lines that are intended as statements, as shown in the following code:

(function() {});
(
[1, 2, 3]
).join(' ');

ASI can bite you in other ways as well. A common example is when you attempt to use a return statement within a function, with its intended return value on the next line. In such cases, you'll get a nasty surprise:

function sum(a, b) {
return
a + b;
}
sum(a, b); // => undefined (odd!)

JavaScript's ASI mechanism will presume that the return statement is terminated if there is nothing else present on the same line, and so the following is closer to what the JavaScript engine will see when running the code:

function sum(a, b) {
return;
a + b;
}

To fix this, we can either place a + b on the same line as our return statement or we can use a group operator to contain our indented expression:

function sum(a, b) {
return (
a + b
);
}

It's not necessary to know every ASI  rule, but it is very useful to know that it exists. The best way of working with ASI is to avoid it wherever possible. If you're explicit about the termination of your statements, then you won't need to rely on obscure ASI rules, and you won't be relying on your fellow programmers knowing these rules either.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.218.221