SoFunction
Updated on 2025-03-10

Introduction to the differences in JS function definition methods

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 function in Example 1 will be loaded into the scope before the code is executed, while Example 2 will only have definitions when the code is executed to that line;
Difference 2: The function declaration will give the function a name, while the 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 nameIf defined by function expression
var factorial = function(num){
//...code
}
//...code
(anotherFactorial);//Output function(){}, anonymous function

The above introduction to the difference in JS function definition methods is all the content I share with you. I hope you can give you a reference and I hope you can support me more.