Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between var function and function in javascript? [duplicate]

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');

}
like image 761
mko Avatar asked Jan 23 '26 10:01

mko


1 Answers

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.

like image 172
James Allardice Avatar answered Jan 26 '26 16:01

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!