Really what is the difference when using semicolons?

1

var f = "hola";

(() => {
  
  console.log(f);
  
})();

This code works perfectly, and I understood that the IIFE , could not access variables and functions outside of this, then is not it?

and I have read about preceding ; to IIFE , but I have not understood much its meaning, I think it would be something like placing the ; alfinal of a functional expression such that:

var a = (function(){

// algo
})();

It would be equivalent to:

 ;(function a(){

// algo
})();
    
asked by Eduardo Sebastian 10.08.2017 в 18:01
source

1 answer

3

The IIFE are any anonymous functions, that is, a function like any other but without a name and if you can read variables that are out, but you have to be careful because you keep the reference of the variables and not their value, for example in the next for you would expect it to print numbers from 0 to 9 but only print 10

//Se podría creer que desplegara los numeros del 0 al 9 pero.....
for(var i=0; i<10; i++)
  setTimeout( ()=>(console.log(i) ), 500);
  

As for the semicolon, it is not mandatory in JavaScript but it is necessary to separate sentences, you can have two lines of code without a point and how and for you it is clear that they are two different instructions for being in separate lines, without However, for javascript no, he is interpreting instruction by instruction and he does not care if it is in two lines or in it, for example:

a="hola"
b="mundo"

For javascript it would be the same as

a="hola"b="mundo"

There the interpreter does not know if that is a sum, multiplication or that it is and it gives you an error

You can put a lot of semicolons and you are simply separating nothing and that the interpreter does not care

;;;var i=0;;;;console.log(i);;;;

To complement the semicolon I leave an example of the ambiguity that occurs by not using a semicolon

//Con punto y coma f1 es una funcion anonima
var f1 = (function(n){return n});
(function(){return 8})()
console.log(f1);

//Sin punto y coma f2 es un 8
var f2 = (function(n){return n})
(function(){return 8})()
console.log(f2);
    
answered by 10.08.2017 / 19:04
source