1

I've seen this in a lot of scripts. When is it better to do

var foo = function() { console.log("Foo!"); };

than

function foo() { console.log("Foo!"); }

when it's obvious that function name(){} is more compact and seems to do the same things? At first, I thought it was so you could use foo as a variable, but you can still do that with both methods. They can even both be redeclared by either method.

I know that var foo = function(){}; creates the function at runtime, but I don't see the advantage of this, because it can lead to crashes, which I assume are unwanted.

Ben Leggiero
  • 25,904
  • 38
  • 161
  • 267
  • @thefourtheye right, like I said, I know the *difference*, I just don't know the *point* – Ben Leggiero Jan 16 '14 at 15:03
  • 1
    Lets say, based on a condition, you want to create two different functions dynamically. Will that be possible with `function ...()` method? – thefourtheye Jan 16 '14 at 15:04
  • I see... `if (bar) function foo(){console.log("bar");} else function foo(){console.log("foo");};` creates when parsing, so despite the value of `bar`, `foo` is always the last-declared version – Ben Leggiero Jan 16 '14 at 15:09

1 Answers1

0

When you define a function as :

function foo() { console.log("Foo!"); }

In simple words, JS engine loads this function before executing the code. However, if you declare a function with var, it is only processed when the js engine starts executing.

foo(); // Fine
foo1(); //Error

function foo() { console.log("Foo!"); }

var foo1 = function(){};
Kiran
  • 5,272
  • 12
  • 52
  • 83