3

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

I've been going through CodeAcademy's Javascript courses, and a few things have gone over my head. I understand how function work, and I'm trying to wrap my head around OOP and objects/methods.

My question is, what's the difference between creating a function like this:

function countTo(number){
    for (var i=1; i<=number; i++){
        console.log(i);
    }
}

countTo(15);

and creating a function like this:

var countToTwo = function(number){
    for (var i=1; i<=number; i++){
        console.log(i);
    }
};

countToTwo(27);

Both do the same thing and have the same output. Are they exactly the same/interchangeable? Does it matter which one I use when creating a function?

Community
  • 1
  • 1
JVG
  • 20,198
  • 47
  • 132
  • 210
  • You are correct - didn't show up for me because the original question wasn't descriptive enough! Thanks. – JVG Dec 11 '12 at 03:41
  • 1
    No problem, it's nice to be redirected to a nice descriptive answer like that. – John Dec 11 '12 at 03:43

1 Answers1

8

The first one is a function declaration, and is "hoisted", meaning it's immediately available anywhere in the context.

The second one is a function expression, and is treated just like any other variable declaration/assignment. The declaration of countToTwo is hoisted and immediately available anywhere in the scope in which it's declared, but the assignment stays in exactly the same place.

The short of it is that you're not able to call a function declared as an expression until the expression has been parsed.

This code should illustrate a little more clearly.

foo();

//blah();

function foo(){
    alert('hoisted and works');
}

var blah = function(){
    // not hoisted, would fail if called
}
​

Live Demo

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393