0

I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.

I want to know the difference between the different way of declaring functions in a sample app.js

var foo = function()
{
  //..
}

function bar()
{
  //..
}

var baz= function()
{
  //..
}

function qux()
{
  //..
}

// other??

I m also not clear about the scope where I can use each function. Thanks!

Orkun Ozen
  • 6,343
  • 7
  • 46
  • 82

1 Answers1

3

There are four ways to create a function in JavaScript.

Function declaration

This will create a variable foo in the current scope and assign a named function to it.

function foo () {

}

Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.

Anonymous function expression

This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.

something = function () {

};

Named function expression

This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.

something = function foo () {

};

Function constructor

Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205