1

When defining a function, what is the difference between these 2 ways:

  1. function t1() {}

  2. var t2 = function() {}

Is t1 a function itself and t2 a reference to function?

Joseph Wu
  • 21
  • 3

1 Answers1

-2

The first one is using the function statement, which is equivalent to doing this:

var t1 = function t1() {};

It's very similar to your t2 example, one difference being that t2 isn't named; It's an anonymous function stored in the t2 variable.


Remember that when using the named function statement (like t1), the var declaration is hoisted to the top of the scope.
That's why this example works, even though it looks like it's calling the function before the function is defined. The function gets hoisted up above the sayHello variable, and that's why it can be used.

The flipside is this example, showing that the t2 example doesn't work because the 'foo' function doesn't get hoisted to the top.

Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
  • Thanks. I figured this out. – Joseph Wu Sep 14 '13 at 07:50
  • Javascript does not compile into javascript. I assume you meant these statements are equivalent. They are not - `t1` is hoisted to the top, `t2` isn't. That's an important difference. – John Dvorak Sep 14 '13 at 08:05
  • No, the statements aren't equivalent. You misinterpreted me. I was actually just going to add that they are hoisted to the top, also, but I was getting some code together as a small example. You're also right about `t2` not being hoisted. I intended to put examples in there but forgot to when I first answered. So thanks for downvoting, it'll look great after I edit it to be correct. – Joe Simmons Sep 14 '13 at 08:11
  • You're rude for downvoting, but at least you didn't prevent me from adding more info for future people to see. – Joe Simmons Sep 14 '13 at 08:19