SoFunction
Updated on 2025-04-03

A brief discussion on the difference in the definition method of JS function

There are two ways to define functions in JS:

(1) Typical function declaration

function slide(arguments){
//...code
}

(2) Define functions in the form of function expressions

var slide = function(arguments){
//...code
}

Although the above two methods are logically equivalent, there are still some small differences:

Difference 1:The functions in Example 1 will be loaded into the scope before the code is executed, while Example 2 will only be defined when the code is executed to that line;

Difference 2:A function declaration will give the function a name, while a function expression creates an anonymous function and assigns the anonymous function to a variable;

See the following example:

function factorial(num){
if(num<=1){
return 1;
}
else {
return num*(num-1);
}
}
var anotherFactorial = factorial;
factorial = null;
(anotherFactorial);//Output factorial(){}, with function name

If defined by function expression

var factorial = function(num){
//...code
}
//...code
(anotherFactorial);//Outputfunction(){},Anonymous functions

The above is all the contents of the brief discussion on the definition of JS functions that the editor brings to you. I hope everyone supports me~