krtkeyan krtkeyan - 1 month ago 6
Javascript Question

What will the reference when both the variable and function have same name in JavaScript?

I have a variable named foo and function named foo.

//variable followed by function declaration
var foo="bar";
function foo(){
return "bar";
}
//function declaration followed by variable
function foo(){
return "bar";
}
var foo="bar";
//When I call foo it returns string bar;
//When I enquired foo() it throws error


What's happening here?Why does the variable name override function declaration?

Answer

When I call foo it returns string bar;

Function declarations are hoisted to the top of their scope. The function definition are moved above by the compiler. And then the variable is overwriting to string.

Code is equivalent as

function foo() {
    return "bar";
}
// Overwriting the value
var foo = "bar"

So, in both the cases, the output will be 'bar'.

Note that function expressions are not hoisted.

For more information on function hoisting, see Javascript function scoping and hoisting

When I enquired foo() it is undefined

foo here is not a function, it's a string. So, foo() will throw an error

Uncaught TypeError: a is not a function(…)

Comments