What happens when JavaScript variable name and function name is the same?

南笙酒味 提交于 2019-11-27 19:08:53

Functions are a type of object which are a type of value.

Values can be stored in variables (and properties, and passed as arguments to functions, etc).

A function declaration:

  • Creates a named function
  • Creates a variable in the current scope with the same name as the function (unless such a variable already exists)
  • Assigns the function to that variable
  • Is hoisted

A var statement:

  • Creates a variable in the current scope with the specified name (unless such a variable already exists)
  • Is hoisted
  • Doesn't assign a value to that variable (unless combined with an assignment operator)

Both your declaration and var statement are hoisted. Only one of them assigns a value to the variable a.

Yosvel Quintero

In JavaScript both function declaration and variable declarations are hoisted to the top of the function, if defined in a function, or the top of the global context, if outside a function. And function declaration takes precedence over variable declarations (but not over variable assignment).

Function Declaration Overrides Variable Declaration When Hoisted

First you declare a variable:

var a; // value of a is undefined 

Second, the value of a is a function because function declaration takes precedence over variable declarations (but not over variable assignment):

function a(x) {
  return x * 2;
}

And that is what you get when you call alert(a);.

But, if instead of declaring a variable you make variable assignment: var a = 4; then the assigned value 4 will prevail.

If you use a function name as variable name, its value is replaced by function body. So "var a" becomes your function "a" body and thus your alert displays function "a".

You should also remember that var a is hoisted, which makes it more like this

var a; // placed

function a(x) {
  return x * 2;
};

var a; // removed
alert (a); // a is replaced by function body

Remember that var a is hoisted, so if you assign 4 to a:

var a; // placed

function a(x) {
  return x * 2;
};

var a = 4; // removed
a = 4 // added

alert (a); // a is now 4

ES6 comes with a better solution by defining SyntaxError: Identifier (?) has already been declared when using let / const instead of var.

let

function foo () {}
let foo;
// => SyntaxError: Identifier 'foo' has already been declared

const

function foo () {}
const foo = 1;
// => SyntaxError: Identifier 'foo' has already been declared

Note that const foo; does not work. It will cause SyntaxError: Missing initializer in const declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!