3

Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}

I am curious to which is best pratice when creating a function in js

function x() {
    ...
}

OR

var x = function() {
    ...
}

Is there a difference or are they the exact same thing.

Community
  • 1
  • 1
austinbv
  • 9,297
  • 6
  • 50
  • 82

6 Answers6

2
x(); // I work
function x() {
    ...
}
y(); // I fail
var y = function() {
    ...
}

The first is a function declaration. You can use functions before you've declared them.

The second is a assigning a function to a variable. This means you can assign to anything.

You can assing it to foo[0] or foo.bar.baz or foo.get("baz")[0]

Raynos
  • 166,823
  • 56
  • 351
  • 396
1

I prefer the first form because it gets defined before variables are defined.

So, you could invoke x in a later scope because the interpreter already defined that function even though it may be declared later on in your code.

This will be simpler with some code:

x(); //logs "hi"

//...
function x() { 
   console.log("hi"); 
}

vs

x(); //fails

var x = function() { 
   console.log("hi");
};
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
1

They are not exactly the same thing, people have mentioned the forward-lookahead difference, here's a less known subtlety - the function name property:

function x(){}
x.name; // "x"

var x = function(){};
x.name; // ""
davin
  • 44,863
  • 9
  • 78
  • 78
0

In the second case, you can pass functions as parameters and store them in arrays

TheHorse
  • 2,787
  • 1
  • 23
  • 32
0

You might find this useful: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope

Alex
  • 64,178
  • 48
  • 151
  • 180
0

The first is a function declaration, the latter is a function expression. Read more here while I try to find a very in-depth article I once read on the differences and implications.

Edit: Ah, here we go. Grab a cup of tea and settle in for an in-depth discussion.

Phrogz
  • 296,393
  • 112
  • 651
  • 745