What does the "+" sign in front of the function mean in Javascript?

Asked

Viewed 455 times

27

Researching a little about form validation on Bootstrap, found the bootstrap-Validator, in which exactly in the file Validator.js, as you can see, it has the notation +funcion. Observe the code below:

+function($) { 
     /* conteúdo */
}(jQuery);

What is the "+" sign in front of the function in Javascript?

  • Related to Soen: https://stackoverflow.com/q/13341698/1452488

1 answer

30


+ is a shortcut, a character of two (), which would be the easiest way to read to invoke a function (...a declaração da função..)().

The + will force the next part to the operator to be interpreted as an expression, ie a function statement and will cause the function to run once it is followed by ().

+function(m) {
  console.log('Olá ' + m + '!');
}('mundo')

Those kind of functions are called IIFE, and this kind of shortened syntax can be done with the converter/operator +, or denial ! or bitwise ~. The idea is to save characters.

!function() {console.log('Usando !');}();

~function() {console.log('Usando ~');}();

-function() {console.log('Usando -');}();

(function() {console.log('Usando ()');})();

Personally I think (function...)() , or the variant (function(){}()), is clearer, and therefore the right way. Therefore not using other operators that have as a function something else, but that as a side effect make the browser to interpret the code and save 1 character.

  • 3

    Sensational response +1

  • 1

    Then the !, ~, - has the same goal of + ?

  • 3

    @acklay in this context yes, but their semantics are different, ie do different things if they are used for the purpose for which they were created. But in this context they all have the same side effect, so they do the same.

  • @Sergio, when ! ~, - can have a different effect?

  • 1

    @Wictorchaves for the purpose of calling a function no, it is equal. But each has a specific function in the context for which it was created. ! is for denial, ~ is bitwise inverter, etc.

Browser other questions tagged

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