Home  >  Article  >  Web Front-end  >  Three types of function expressions in JavaScript

Three types of function expressions in JavaScript

韦小宝
韦小宝Original
2018-03-10 11:56:311753browse

Expression(expression)A phrase in JavaScript, JavaScript will calculate (evaluate) it to produce a result. A constant in a program is the simplest expression. Variable name is also a simple expression, and its value is the value assigned to the variable. Complex expressions are composed of simple expressions. For those who don’t know much about it, let’s take a look at the three function expressions in JavaScript!

The function name is a required part of the function declaration statement. Its purpose is like the name of a variable to which the newly defined function object will be assigned. For function definition expressions, this name is optional: if present, the name is stored only in the function body and refers to the function object itself.
Note:
Defining a function with an expression is only applicable when it is part of a large expression, such as defining a function during assignment and call.

1. Declarative functions

  function area(width,height) {
       return width*height;     
  }
  var size = area(3,4);

The interpreter will search for variables and declarative functions before executing each script. This indicates that the function can be called at a position before its declaration.



2. Expression function

var area = function(width,height) {
     return width*height;
};
var size = area(3,4);

The function cannot be executed before the interpreter finds this statement.



3. Anonymous function

var area = (function() {
var width = 3;
var height = 5;
return width*height;
}());

Call this function immediately, generally only runs once.

Define functions as function expressions, and the name of the function is optional. If the function name is defined, the function name will become a local variable inside the function (very suitable for recursion). Function definition expressions are particularly suitable for defining functions that will only be used once.

Related recommendations:

#Another way to convert js function declarations into function expressions

The above is the detailed content of Three types of function expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn