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

前端 未结 5 900
南方客
南方客 2020-11-29 03:45

I have the following code, where I declare a function and after it, a variable with the same name as the function:

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

var a         


        
5条回答
  •  迷失自我
    2020-11-29 04:00

    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.

提交回复
热议问题