What is the correct way to declare a javascript function? [duplicate]


For some time, I have been observing the use of two forms of declaration of function javascript , being the following:

- Form 1:

function soma1(val1, val2){
    return val1 + val2;

- Form 2:

var soma2 = function(val1, val2){
    return val1 + val2;

The two forms seem to work equally well.

My doubts are as follows:

  • Is there any right or wrong way?
  • Is there any standard form considered?
  • Are there differences between the two forms? (from: performance, execution context, etc.)
  • Are there any recommendations for use?
  • asked by anonymous 20.03.2015 / 21:55

    1 answer


    There is a difference between them, so there is no right way to say it. Each has a purpose.

    The preference must be for the first form, it can be considered the default. This is the normal function declaration. And it may be slightly faster depending on the implementation of JavaScript. But I've seen obvious and intuitive things work the other way around.

    The second form is not creating a traditional function. You are creating what is called anonymous function . You associate the code written to it with a variable and it can be transferred to other parts of the application providing great flexibility when it is required.

    In this form the function only exists logically (it is in scope) as long as it has a variable holding it.

    It has an added advantage that it can work as a cloister . That is, it can save a value obtained through a variable that was declared in the scope of the function that created this anonymous function. In other words, it holds this value inside the anonymous function and can use it as long as it is "alive."

    An anonymous function can be returned from the creative function as a result of it. It can also be passed as an argument to another function that expects a code to execute. Another use is as the value of a member of an object. Rarely does it have utility if it is not passed to other points of the application in some way. Normal function can also do this but if it is programmed within the standards it is rarer to be useful to do this.

    In the linked questions there is more information about how the second works because this is not the focus of this question.

    Example use of anonymous function:

    function criaFuncao() {
       return function() { print("oi"); };
    var codigo = criaFuncao();
    codigo(); // vai imprimir oi
    20.03.2015 / 22:12