Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner Javascript: What's the difference between 'function xyz(){}' and 'var xyz = function(){}'? [duplicate]

Tags:

javascript

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?

like image 826
JVG Avatar asked Dec 03 '25 17:12

JVG


1 Answers

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

like image 166
Adam Rackis Avatar answered Dec 06 '25 09:12

Adam Rackis