为什么函数声明会被提升而函数表达式不会?

Why do function declarations get hoisted and function expressions don't?

根据吊装定义:

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution

为什么函数声明会被提升而函数表达式不会?

根据MDN,

Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

如您所见,在函数表达式中,实际函数是分配给命名变量的值。所以这个命名变量被提升了。即使您分配了命名函数,它仍然不会被提升,因为它不是声明,将在稍后创建。

样本:

function test() {
  console.log(fn, foo);
  
  var fn = function foo() {}
}

test();