The difference between function declaration and function expression in JS

1. Function definition

The most common ways to define functions in JavaScript are function declarations and function expressions . The two technologies are very similar and sometimes indistinguishable, but there are subtle differences between them.

The most basic way to define a function in JavaScript is a function declaration :

Insert image description here
Function declarations must stand alone, but can also be included in other functions or blocks of code .

// 全局独立声明函数tom
function tom() {
    
     
  return "tom here"; 
}
// 全局独立声明函数jerry
function jerry() {
    
     
  // 在jerry函数体中声明函数hiddenTom
  function hiddenTom() {
    
     
    return "jerry here"; 
  }
  return hiddenTom(); 
} 

Function expression:

Functions in JavaScript are first-class objects, which among other things means they can be created via literals, assigned to variables and properties, and passed as arguments to other functions or as return values ​​from functions.

var a = 3;
myFunction(4); 

Likewise, a function literal can be used in the same position:

var a = function() {
    
    }; 
myFunction(function(){
    
    });

Such functions that are always part of other expressions ( either as rvalues ​​of assignment expressions or as parameters of other functions ) are called function expressions.

In addition to the different locations in the code, function declarations and function expressions have another more important difference: for function declarations, the function name is mandatory, while for function expressions, the function name is completely is optional.

2. Function declaration interview questions:

Read the code snippet below, categorized according to function type (function declaration, function expression, and arrow function).

// 1
numbers.sort(function sortAsc(a, b) {
    
    
  return a– b;
});
// 2
numbers.sort((a, b) => b– a);
// 3
function outer() {
    
    
  function inner() {
    
    }
  return inner;
}
// 4
(function() {
    
    })();
// 5
(function() {
    
    }());
// 6
(() => "Yoshi")();

Write the answer in the comments

Guess you like

Origin blog.csdn.net/ThisEqualThis/article/details/128836136