What will the reference be when a variable and function have the same name?

javascript

Solution

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(…)

Problem

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?

Original source

Related problems