-1

I ran across these two examples. Example 1 is not valid JavaScript - it throws an error. The second example is valid and works fine. Is there any chance someone can explain why 1 throws an error?

Example 1:

var
  laugh
;

laugh();

laugh = function () {
  console.log( "Hahaha!!!" );
};

Example 2:

laugh();

function laugh() {
  console.log( "Hahaha!!!" );
}
randombits
  • 47,058
  • 76
  • 251
  • 433

2 Answers2

3

It's something called "hoisting" is javascript. Some blog post on the topic: http://jamesallardice.com/explaining-function-and-variable-hoisting-in-javascript/

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
1

Assuming you mean that option 1 is invalid and option 2 is valid:

this is a classic pitfall in JS. basically, in your first function, you declare the variable laugh as an anonymous function, but that doesn't turn it into a function which you can execute by laugh(). however, in the second example, you explicitly declare the function laugh, which you CAN execute by laugh().

edit for below comment: as a correction: you CAN execute the function, but you need to declare it BEFORE executing. else it is undefined. JS makes a list of all functions during compile so they can be executed before they are declared,, but variables are declared and assigned at runtime, so they need to be assigned BEFORE executing.

edit2: vkurchatkin has a good link to what i'm talking about.

Nzall
  • 3,439
  • 5
  • 29
  • 59
  • If you swap the order of 1 so that you set the value of `laugh` before calling `laugh()`, it will work fine. – Evan Davis Oct 28 '13 at 15:53