Distinguishing Function declaration and Function expression

Tram Ho


The question is: where are they different?

  • The difference is that: the function declaration can be invoked to be used anytime, anywhere by the browser interpreter. JavaScript knows its presence and parse it before our JavaScript program executes. In other words (more abstractly), JavaScript puts functions of this type on top of the current scope.

In the above example we see the test () function is called before it is declared. However, we can also write the following format:

What about the function expression? It is not evaluated by JavaScript until it is assigned to the variable. A little abstract, we can make an example easy to understand

If you run the code above, you will get an error because the expression is called before it is declared. To run, we must rewrite the following:

=> function declaration, you can call before declaring or after declaring all, and function expression must have sequence.

Function Declaration

  • When you create a function named, that is called a function declaration

Function Expression

  • Or using the syntax es6 creates an anonymous function (declaring a function but not using the function keyword) is also a function expression.

  • Nature:
    • As for the nature of the function declaration and the function expression are different in the scope of influence. With the function declaration, the name of the function will exist in its scope and its parent scope (where it was created), and with the function expression, the name of the function (if any) will only appear in its scope, and it will not exist outside the parent scope. Another important thing, the function expression will not be hoisting like the normal function.

Hoisting

  • The concept of hoisting denotes a function or variable that can be “invoked” from the first line of code, before they are declared.
  • Function Declaration has a hoisting property and Function Expression does not, this can easily be expressed through the following two examples: The following code will execute normally when using Function Declaration

For Function Expression, the error will be

Use circumstances

  • Through the above two sections, we can see that the Function Declaration and Function Expression are mainly different because the Hoisting and Function Declartion properties seem to be stronger because of the scope of use, but in reality we should only consider scope to use the correct Function Declaration, to avoid having too many unnecessary functions in the global scope.

summary

  • We use the declartion function when we want to create a function that can be used anywhere in the entire code and use the function expression when the function is restricted to use, making the global scope lighter and cleaner.
Share the news now

Source : Viblo