Pitfalls in IIFE in JavaScript

Let's look at two pieces of code.

First:

let result = 1 +function() { return 2; }(); console.log(result);

Second:

let result = 1; +function() { return 2; }(); console.log(result);

These two pieces of code are almost the same, but if you run them, the result will be different. The first code will print the number 3 to the console, and the second - the number 1.

Why there is such a difference: the whole point is that in one case in the first line of the code at the end there is no semicolon, and in the second case it presents.

You may ask: how is that, because in JavaScript, the semicolon at the end of the command is not required! Actually this is not true. Let's take a look at what's really going on.

The first code can be rewritten like this:

let result = 1 + function() { return 2; }(); console.log(result); // shows 3

Now it immediately becomes obvious that the result of calling the function in-place, that is, 2, is added to one. Therefore, the final result will be 3.

If you put a semicolon after one, then the code will be perceived by the interpreter differently:

// First command: let result = 1; // Second command: +function() { return 2; }(); // Third command: console.log(result); // shows 1

That is, assigning to a variable and calling a function in-place will become different commands. And all because of the semicolon!

It turns out that in this case, calling the function in-place does nothing at all - it just returns to nowhere the number 2, which does not affect the variable result.

Let's then figure out why we can not write a semicolon in JavaScript at all. Suppose we have such code without semicolons:

let result = 1 // 1 will be written to the result let test = 2 // 2 will be written to the test

It works correctly, because the interpreter itself placed a semicolon at the end of each line.

But look at this code:

let result = 1 + 2; // 3 will be written to the result

Now the semicolon at the end of the first line is not automatically inserted, because the interpreter understands that the second line command is part of the first line command.

But if we put a semicolon ourselves, the result will be completely different:

let result = 1; // 1 will be written to the result + 2; // the command does nothing, but there will be no error either

It turns out that the interpreter itself puts a semicolon only if the next command is not part of the previous one.

Now look at this code:

let result = 1 +function() { return 2; }(); console.log(result);

Indeed, the second line is just a continuation of the command from the first line, and the interpreter does not automatically insert a semicolon. That is why, if we ourselves write a semicolon at the end of the first line, the result will be completely different. This suggests that it's best to always put semicolons in the right places to avoid problems.

enru