Javascript defines the difference between a function statement and an expression

  • 2020-03-30 01:13:03
  • OfStack

After years of using javascript and writing countless functions, it is a tragedy that today I am only able to truly understand the difference between the two function definitions. I wrote this essay to remind myself to lay a good foundation and not to be confused at an old age.

In general, we see two ways to define a function:


//Function statements
function fn(str)
{
  console.log(str);
};
//Expression definition
var fnx=function(str)
{
  console.log(str+ ' from fnx');
};

Before is to rely on their fingers feel free to use both -_| |, today to see the js foundation, finally is to solve their confusion in the mind:

Two ways to create a new function object, but the function declaration statement function name is a variable name, variable pointing to the function object, and through the var statement variable, the function in the function definition statement is explicitly to the top of the script or function in advance, so they are within the scripts and functions are visible, but using var expression definition function, only the variable declarations in advance, variable initialization code is still in the original position, with the function statement create function, the function name and the function body are in advance, so we can use it before it is declared.


Related articles: