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

前端 未结 5 904
南方客
南方客 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

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

    Edit But if you assign value to a like var a = "xya";. Then it function will be replaced by variable. As per Order of precedence

    1. Variable assignment takes precedence over function declaration
    2. Function declarations take precedence over variable declarations

提交回复
热议问题