+ sign before the function in JQuery? what does it mean? [duplicate]

6

I'm going to finish a system started by another colleague who was disconnected from the company and I'm in doubt about using + before starting the function, and I would like to know what the impact of this assignment is,

+function ($) {

//funções dentro do arquivo .js
//e termina dessa forma

}(jQuery);

I'm used to working in two ways;

  • $(function ($) {...})
  • $(document).ready( function() {...})
  • asked by anonymous 28.09.2017 / 14:10

    1 answer

    4

    The + in front of the function is for executing it immediately IIFE ( Immediately Invoked Function Expression) . If this operator does not exist or any other way of indicating that the function will be executed immediately the declaration will not be considered as an expression by the parser of the browser.

    In the case of your example, you are executing the function immediately after defining it, passing as a parameter the JQuery variable. In the case of your first example, you can use other syntaxes too, such as the following:

    (function ($) {
    
    //funções dentro do arquivo .js
    //e termina dessa forma
    
    })(jQuery);
    

    You can use any unary operator to have the same result:

    !function(){ /* implementação */ }();
    ~function(){ /* implementação */ }();
    -function(){ /* implementação */ }();
    +function(){ /* implementação */ }();
    
        
    28.09.2017 / 14:15