0

By trying to override a function I occurred in this odd behaviour. I hope to find an answer after having searched and read about function declaration methods without success.

In a script, if I declare this

var someFunction = function(){
    alert("a");
}

someFunction();

someFunction = function(){
    alert("b");
}

By calling someFunction I will have an output of "a"

But if I declare the two functions in this way

function someFunction(){
    alert("a");
}

someFunction();

function someFunction(){
    alert("b");
}

My output will be "b"

What is the difference here? I understand the first example is assigning to a variable an anonymous function. But the second example is totally unexpected and new to me.

I tested on all browsers and the output is the same.

Jonathan
  • 738
  • 8
  • 22

1 Answers1

0

The difference is the fact you are calling an anonymous function in the first example, Javascript gets evaluated top to bottom. In the case of an anonymous function it isn't actually executed UNTIL it is called later on.

Ian
  • 3,539
  • 4
  • 27
  • 48
  • I understand the first example, but why the second is acting like this? – Jonathan May 04 '17 at 10:24
  • Try giving http://stackoverflow.com/a/336868/3604087 a read – Ian May 04 '17 at 10:25
  • @Jonathan Because you are declaring your function in global scope. And you can write your function at the end of your .js file, but still can call it on the first line. And after second declaration of `someFunction` you overrides the first one. – tadej May 04 '17 at 10:26