I have been using JavaScript for many years and have written countless functions. But today I really understand the difference between the two function definitions. It is really tragic. I wrote this essay to remind myself to lay a good foundation. I am too old to continue. I understand.
Usually we see the following two ways of defining functions:
//Expression definition
var fnx=function(str)
{
console.log(str ' from fnx');
};
Both methods create new function objects, but the function name in the function declaration statement is a variable name, and the variable points to the function object. Just like declaring variables through var, the function in the function definition statement is explicitly advanced to the script. or the top of the function, so they are visible throughout the script and within the function, but using var expressions to define functions, only the variable declarations are brought forward, the variable initialization code is still in the original place, the function created with the function statement, the function name and the function body are prepended so we can use it before declaring it.
The code example is as follows:
console.log(typeof(fnx)); // undefined
if(fnx)
fnx('abc'); // will not execute
else
console.log('fnx is undefined'); // fnx is undefined
// Function statement
function fn(str)
{
console.log(str);
};
// Expression definition
var fnx=function(str)
{
console.log(str ' from fnx');
};