Reviewing JavaScript code, I saw these two types of functions:
function EjemploUno(){
//código
}
var EjemploDos = function(){
//código
}
So, what is the difference between one and the other? When should you use one or the other?
Reviewing JavaScript code, I saw these two types of functions:
function EjemploUno(){
//código
}
var EjemploDos = function(){
//código
}
So, what is the difference between one and the other? When should you use one or the other?
The difference is that in the first case it is a named function
EjemploUno
while in the second case it is an anonymous function assigned to a name variableEjemploDos
We can easily verify this with the property
.name
as can be seen in this code snippetIn the first case we get the expected result
EjemploUno
while in the second we get an empty string since the function is anonymousSince the name of the function is not the same as the name of the variable that the function is assigned to, we can also have the following:
In which case it is a named variable
EjemploTres
that has a named functionEjemploCuatro
In the last case we see how the name corresponds to
EjemploCuatro
and notEjempoTres
since this is the name of the function and not of the variable.The two forms are used to declare functions in Javascript and the differences are not only in the way the variables are assigned but there are semantic consequences when using one or the other method to declare them. Let's go by parts:
This is what is known as a function definition and is used to declare a function and assign it to the identifier or variable
EjemploUno
. I have also seen the term function declaration used to refer to it.Note: This structure does NOT require the use of a
;
at the end of its declaration.The consequence of declaring functions this way is that the Javascript interpreter when it encounters something like that hoists the variable and includes the body of the function . An example of this can be seen in the following code snippet.
The first instruction
alert
refers to a variable that is declared 6 lines of code below, however it shows you the content of the function (alert internally uses toString() to show the object that you want to represent) however the secondalert
showsundefined
what happens because the identifier is declared but no value has been assigned to it . The assignment only happens 9 lines of code below when the statement is executedEjemplo2 = function()
That second case is what is known as a function expression that can be anonymous or not. Both forms REQUIRE the use of a
;
to separate them from the next statement. Example:The difference between the two ways above is that when the variable
Ejemplo2
is assigned another value, the anonymous function will be marked by the garbage collector for removal, as long as it has not been assigned elsewhere since there is no variable doing it. reference so it is impossible to retrieve it again.In the case of the named function expression it is possible to do something like this:
The MyFunc identifier can be saved and you can continue to refer to the function even if
Ejemplo2
it is set to another value. This is very handy for referencing the function within itself; for example to deregister events within themselves as shown in the following code snippet:Clicking the button removes the event as there is a reference to the function used to register it.
The other uses that can be given to this pattern is that in case of an exception the source of the problem can be easily identified as the function name will be displayed on the error stack and can be used to create recursion. Example:
UPDATE
There is another case where the differences become more noticeable, and that is when the code is executed in strict mode and EcmaScript 5 is enabled, which establishes some requirements, such as that function declarations can only be used in the upper level block, that is, you should not do something like this:
The code above does not generate errors in some environments but the reason for this is because of browser extensions to the ECMA-262 standard , which specifies that function declarations cannot be used everywhere , a restriction that does not apply to Expressions . of function . This link has information on why the standard makes such a claim.
UPDATE 2
The last case where the differences are seen is that in Ecmascript 6 there is already block scope, which completely changes the semantics of a function declaration if it is inside a code block like the previous example. According to the standard this should happen:
This is something that is still in the process of being implemented, but it is recommended that you do not write code that could be considered illegal so that what you write can better survive future changes that the language may experience, so it is important that you know the differences between the two structures.
Your question can be summed up in that they are completely different from the language point of view (even in the spec they are divided http://es5.github.io/#x12.4 and http://es5.github.io/ #x13 ) having the similarity that both can be used to declare functions.
Here
JavaScript Function Definitions
explain what you mean
when you define
You are not defining a name for the function, but you assign it to a variable, and it is through this that you execute it.
It's the same when you do something like this
In this case you are passing an anonymous function as a parameter.
Named functions: are those functions that receive a name in their declaration.
Functions by expression: their name is optional in their declaration, if they do not have it, they are also called anonymous functions.
Differences:
this
) is different, it depends on where it is executed.Example:
The execution results would be:
Anonymous functions are commonly used:
Useful example (anonymous function)
Exercise: Taking into account that you have a site in which you want to list each published image and that its corresponding number is displayed in the console each time the user hovers over it.
We could easily do something like the following:
In the case above, we would have an unexpected result, because it would always return the same index for all images (regardless of position) and this number would be equal to the length of images on our site. While the following code shows us:
Here we would have the expected result.
What is the behavior due to?
In the first case, the variable
i
will increment by modifying its previous value, so that when anmouseover
image is done, it is calledi
with the last value set in the loop (at its last iteration).In the second case (anonymous-self-executing function), we can see that it is being passed
i
as a parameter, so that it is received as a new scope that will remain that way until it is modified inside, therefore its reference toi
maintains the value of when was received.In the first, the function is assigned to the variable foo(It is a generic term widely used to refer to any computing entity whose name is ignored) at run time.
In the second, the function is assigned to that identifier foo, at parse time.
Reference
In short: ExampleOne is a declared function and ExampleTwo is an expressed function.
What does it mean? Before executing the code, the javascript engine reads the declared functions and does not read the expressed functions until the code is executed.
Implying? Let's see it in two examples:
It throws an error because ExampleTwo, in addition to being a function, is also a variable that in this case has not been declared.