Semicolon for safety in IIFE

Let now our function called in-place not be with a plus at the beginning, but wrapped in parentheses, like this:

(function() { console.log(1); // shows 1 })();

Let the variable num be set outside the function:

let num = 1; // semicolon is put (function() { console.log(num); // shows 1 })();

Let now we forgot to put a semicolon:

let num = 1 (function() { console.log(num); //!! will throw an error })();

It turns out that such code will generate an error, since JavaScript perceives our function as a continuation of the first line command.

To avoid such problems, you should always put a semicolon before calling a function in-place, like this:

let num = 1 ;(function() { console.log(num); // shows 1 })();

The problem seems to be somewhat contrived. Actually, it is not. There may be such a situation that several scripts from separate files are connected on your page. In this case, a semicolon can be omitted at the end of one file, and this will automatically lead to a problem if the second file starts with an in-place function call.

Therefore, always, always put a semicolon before calling a function in-place, even if you are currently sure that there will be no problems. They may come later.

Let's apply the above and call the function in-place, putting a semicolon at the beginning:

;(function() { console.log(1); // shows 1 })();

Determine what will be output to the console without running the code:

let str = 'str'; (function() { console.log(1); })();

Determine what will be output to the console without running the code:

let str = 'str' (function() { console.log(1); })();
enru