Using ';' before starting a [duplicate]

6

It has become common for me to find codes in github that start like this:

;(function(window){
    'use strict';
})();

I just never understood the following. What is the purpose of using ';' before starting the function declaration?

    
asked by anonymous 19.03.2015 / 15:14

2 answers

9

Semicolon is used to make sure that the previous statement has been terminated.

For example:

  
(function() {

})()  // <--- Não tem ponto e vírgula

//  Adicionado ponto e vírgula para evitar um resultado inesperado do código anterior   
;(function ($) {

})();

The name of this technique is IIFE ( Immediately-Invoked Function Expression ).

    
19.03.2015 / 15:25
8

Auto-invocation functions are built between parentheses, putting a semicolon before the function start can prevent the function from becoming part of any predecessor code, note that:

The code

var a = 10 

(function(){...})()

It's the same as

var a = 10 (function(){...})()

Now putting the semicolon, you avoid this type of eventual problem in your code

var a = 10 

;(function(){...})()
    
19.03.2015 / 15:32