3

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Function declaration - Function Expression - Scope

I've learned about var a = 1, is defining a local variable, but talk about function, I thought It's only available within the current scope as the var variable behave, what's the difference between the following two code snippet?

function aPrint() {
console.log('a');
}

var a = function aPrent() {
console.log('a');

}
Community
  • 1
  • 1
mko
  • 21,334
  • 49
  • 130
  • 191

2 Answers2

2

Your first example is a "function declaration". It declares a function that will be available anywhere in the scope in which it is declared (so you can call it before it appears in the source code). This is sometimes known as "hoisting" (as in, it gets hoisted to the top of its scope).

Your second example is a "named function expression". The variable declaration is hoisted to the top of the scope in which it is defined (like a function declaration) but the assignment still happens where you expect it to, so you can't call the function until after it has been assigned to the variable.

There is a third option, which is just a "function expression", where the function does not have a name (it's an anonymous function):

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

You will probably find that you have little use for named function expressions (although it can be useful when debugging), so it's usually better to use the anonymous function. In a named function expression, the name is only in scope inside the function itself, so you can't refer to the function by name normally.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
-1

here is a best article that may help you.

refer http://www.dustindiaz.com/javascript-function-declaration-ambiguity/

  1. function aPrint() {} Declares a function (but does not execute it). It will usually have some code between the curly brackets.

  2. var a = aPrint() Declares a variable, invokes a function (aPrint) and sets the value of aPrint to the return of the function.

  3. var a= new aPrint() Creates a new instance of an object based on the aPrint function. So the variable is now an Object, not just a string or a number.

Objects can contain indexed strings, numbers and even functions, and you can add more stuff to them, they're pretty awesome. The whole concept of Object Oriented Programming (OOP) is based on this.

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91