Use of ';' before starting a function

Asked

Viewed 125 times

6

It has become frequent for me to find codes on github that start like this:

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

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

  • 3

    It has the sources of these functions that originated the question?

  • 1

    https://github.com/fians/Waves/blob/master/src/js/waves.js This is an example...

  • 2

    Related questions: http://answall.com/questions/38379/a-aus%C3%Aancia-de-ponto-e-v%C3%Adrgula-no-css-e-javascript-pode-influenciar-no-funcioname? lq=1, http://answall.com/questions/3341/utilizar-ou-n%C3%A3o-ponto-e-v%C3%Adrgula-no-fim-das-linhas-no-javascript

2 answers

9


The semicolon is used to make sure that the previous instruction has been completed.

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).

  • 1

    Doing a search in English I found this here too: http://stackoverflow.com/questions/7145514/whats-the-purpose-of-starting-semi-colon-at-beginning-of-javascript Thanks for the answer! : D

8

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

The code

var a = 10 

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

Is the same as

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

Now putting the dot and comma, you avoid this kind of eventual problem in your code

var a = 10 

;(function(){...})()
  • 2

    Excellent addition. =)

  • 2

    @Qmechanic73 noticed that you had already answered, but as I was already writing I took the opportunity to post :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.