Functions 1: function declarations and function expressions

  • 2020-03-30 03:26:26
  • OfStack

Function declaration


function foo() {}

The function foo will be hoist (promoted) before the entire program executes, so it is available in the entire scope (scope) that defines the foo function. It's okay to call it even before the function is defined.


foo(); // Works because foo was created before this code runs
function foo() {}

I'm not going to go into detail here because I'm going to write a special article on scope.

Functional expression

For function declarations, the name of the function is required, but for function expressions it is optional, so anonymous function expressions and named function expressions appear. As follows:

Function functionName (){& provident; }
Function functionName[optional](){& functionName; }
So I know that if I don't have a function name, it must be a function expression, but how do I know if I have a function name?
Javascript specifies that if the entire function body is part of an expression, it is a function expression, otherwise it is a function declaration. The following is the expression:


var fuc = foo(){}

Let's take a few more extreme expressions:


!function foo(){}
true && function foo(){}

The above statement here is just to distinguish the function expression, it is not normally written like this. Here's a comparison:


foo1();//foo1 is not defined 
foo2();//works because foo2 was created before this code runs
!function foo1() {
  alert('foo1 works');
};
function foo2() {
  alert('foo2 works');
};

Anonymous function expression


var foo = function() {};

The above example assigns an anonymous function to the variable foo.


foo; // 'undefined'
foo(); // this raises a TypeError
var foo = function() {};

Because var is a declaration, the variable foo is hoist (promoted) so that the variable foo is invoked when the program executes.
But since the assignment statement only takes effect at run time, the value of the variable foo is undefined.

Named function expression

The other thing I want to talk about is the assignment of named functions.


var foo = function bar() {
  bar(); // Works
};
bar(); // ReferenceError

In this case, the named function bar is assigned to the variable foo, so it is not visible outside the function declaration, but can still be called inside the bar function. This is because of the way Javascript handles named functions, whose names are always valid within the scope of the function.


Related articles: