21

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?

Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
krtkeyan
  • 239
  • 1
  • 7
  • both cases will return the string "bar". basically functions are hoisted to the top of the file . so the string "bar" will replace them in both cases . -- it shouldn't return undefined it should raise an error . – Ahmed Eid Oct 17 '16 at 03:20

5 Answers5

15

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

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • @Tushkar it did throw an error, it's my mistake stating foo undefined. Anyway thanks for your answer. – krtkeyan Oct 17 '16 at 03:30
2

In a clearer and more explicit way of declaring variables, the latter will take account:

    var foo = "bar";
    var foo = function () {
        return "bar";
    };
    console.log(foo);

output is a function

and the reversal:

var foo = function () {
    return "bar";
};
var foo = "bar";
console.log(foo);

has "bar" as output.

Bob Dust
  • 2,370
  • 1
  • 17
  • 13
1

In JavaScript, functions are processed upon entering the corresponding scope. The variables are processed when the interpreter gets to their declaration. Therefore in your example, the functions are processed first, the name foo is used by the last function and then overwritten by the variables.

Note that if you declare your function like this

var foo = function() {}

it is actually not processed at the beginning and also overwriting the variables declared beforehand.

mxscho
  • 1,990
  • 2
  • 16
  • 27
0
var foo="bar";

var foo = function(){
  return "bar";
};

They are the same. Don't miss to put ; in the end of line.

Jared Chu
  • 2,757
  • 4
  • 27
  • 38
0

both cases will return the string "bar"

basically javascript grabs all functions and put them in the top of the file its called hoisting .

so the string declaration will overwrite the function expression in both cases ;

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34