Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Function declaration style

Tags:

javascript

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?

like image 442
CuriousMind Avatar asked Dec 16 '22 08:12

CuriousMind


2 Answers

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.

like image 96
Li0liQ Avatar answered Dec 29 '22 22:12

Li0liQ


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).

like image 42
Quentin Avatar answered Dec 30 '22 00:12

Quentin