1

I called helloworld and defined it with below two different ways:

1) With variable

2) With function name itseld

var helloWorld = function() {
    return '2';
}

function helloWorld() {
    return '1';
}

alert (helloWorld());  // This alert 2, but in absence of "var helloWorld = ....", it alert "1".

Can anyone please explain reason why it's calling var helloWord = ? and not function helloWorld () ?

Thank You !!

CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36
  • Read this: https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ – lintmouse Feb 29 '16 at 16:42

1 Answers1

11

why it's calling var helloWord = ? and not function helloWorld () ?

Because functions definitions will be hoisted to the top. And the assignments remains in the same place. So it is getting overridden.

This is how the interpreter sees the code,

function helloWorld() {
    return '1';
}

var helloWorld;

//the above function is getting overridden here.
helloWorld = function() {
    return '2';
}

alert (helloWorld());
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • There's a great demonstration of this kind of variable and function hoisting here: https://github.com/loverajoel/jstips/blob/gh-pages/_posts/en/2016-01-11-hoisting.md – BurpmanJunior Feb 29 '16 at 16:45
  • [A Drop of Javascript](http://adripofjavascript.com/blog/drips/variable-and-function-hoisting) also has an article about this. – h2ooooooo Mar 02 '16 at 12:51