Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

named functions vs named variables with functions

Hello all, I'm trying to grasp when I would want to create a named function vs a named variable and assigning it to a function. For example:

var sendAJAX = function(){
  xhr.send();
}

vs

 function sendAJAX(){
     xhr.send();
   }

My past JAVA experiences have followed the second approach but since I been doing the Javascript course on treehouse sometimes I see the teachers create functions as variables. When would I benefit from the first or the second one? Thanks

2 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

In addition to what Erik wrote;

If you use the first approach order matters. Meaning if you were to write something like this:

sayHello(); //This would not work

var sayHello = function() {
    console.log('hello');
}

You have to declare the function before you use them.

The second approach, you don't have to think about that.

sayHello(); //This works

function sayHello() {
    console.log('hello');
}
Erik Nuber
Erik Nuber
20,629 Points

Thanks, I forgot about that too! That is definitely important.

Oh ok thanks guys I can see how they both are virtually the same but yea that's a good call out. If its defined as a variable I would have to declare the variable first otherwise it will generate a runtime error of variable undefined.

Erik Nuber
Erik Nuber
20,629 Points

They are virtually the same thing. However, when you declare a variable a function, you can always reassign the variable to something different. This would work with any variable. If you assigned

var someNum = 4

someNum = 10

In this way assigning a variable to a function it could achieve the same thing. i don't really know why you would ever want to change a function but, here is an example from Eloquent JavaScript.

var launchMissiles = function(value) {
  missileSystem.launch("now");
};
if (safeMode)
  launchMissiles = function(value) {/* do nothing */};