4

In Javascript, I have seen three different ways to define a function.

  • Conventional style:

function foo() { //do something }

  • New Js Ninja Style

var foo = function(){ //do something }

  • DOM specific style

window.foo = function(){ //do something }

What question is,

What is the difference between the above three? And which one should I be using & why?

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
CuriousMind
  • 33,537
  • 28
  • 98
  • 137

2 Answers2

11

The first one is function declaration. It is hoisted (you could use it anywhere inside current scope).

The second one is a variable definition using anonymous function. Variable is hoisted, assignment stays in place. The function may not be used until the line where you assign it.

The third one is assigning a global method. Similar to the second one, although works with global object, which is not good.

Yet, you could think about the fourth alternative(named function expression):

var foo = function bar(){ //do something }

Here, bar will be available only inside itself, which is useful for recursion and not churning current scope with it.

You are selecting any approach based on your needs. I'd only vote against the second approach, as it makes function behave like a variable.

As soon as you mention both the second and the third option, I'd like to remind that polluting global object is considered bad practice. You'd better think about using self-executing anonymous functions to create separate scope, e.g.

(function(){
    var t = 42; // window.t still does not exist after that
})();

I suppose you may find a more detailed article on JavaScript Scoping and Hoisting useful.

Community
  • 1
  • 1
Li0liQ
  • 11,158
  • 35
  • 52
  • What is meant by its "hoisted"? Further, what is the downside is I declare using 2nd Approch. Because from my limited understanding of javascript, everything is is an object -- variables, function. – CuriousMind Oct 11 '11 at 18:02
  • You could refer to the article I've mentioned for additional details. In short, all the variable and function declarations are internally hoisted(lifted) to the beginning of the current scope. First functions, then variables. Assignments are left where they are. – Li0liQ Oct 11 '11 at 18:06
  • Excellent post + that article is great aswell. – JonnyRaa Jun 30 '14 at 13:30
2

First, see Javascript: var functionName = function() {} vs function functionName() {}.

Then we get to the difference between var foo = and window.foo =.

The first is a locally scoped variable which is nice and lovely (unless it is done in the global scope). The second is a an explicit global, which has all the usual issues of globals (such as likelihood of conflicting with other code).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335