English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

A Brief Discussion on the Differences in JS Function Definition Methods

There are two ways to define functions in JavaScript:

(1)Typical function declaration

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

(2Define the function in the form of a function expression

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

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

Difference one:The function in example one will be loaded into the scope before the code execution, while example two will be defined when the code reaches that line;

Difference two:Function declaration assigns a name to the function, while function expression creates an anonymous function and then assigns this anonymous function to a variable;

See the following example:

function factorial(num){
if(num<=1){
return 1;
}
else {
return num*arguments.callee(num-1);
}
}
var anotherFactorial = factorial;
factorial = null;
console.log(anotherFactorial);//Output factorial(){} with a function name

If defined as a function expression

var factorial = function(num){
//...code
}
//...code
console.log(anotherFactorial);//Output function(){} as an anonymous function

This is the full content of the brief introduction to the difference in the definition of JS function methods brought to you by the editor. I hope everyone will support and cheer for the tutorial~

You May Also Like