Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Suppose we are inside a function and not in the global namespace.
function someGlobalFunction() { var utilFunction1 = function() { } function utilFunction2 () { } utilFunction1(); utilFunction2(); }
Are these synonymous? And do these functions completely cease to exist when someGlobalFunction
returns? Should I prefer one or the other for readability or some other reason?
A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call. But a function can be a variable, too, as it stores data and values, too. See the following syntax: var functionname = function(){} .
Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).
The Excel VAR function estimates the variance of a sample of data. If data represents the entire population, use the VARP function or the newer VAR. P function. VAR ignores text values and logicals in references. Get variation of a sample.
They are mostly the same.
utilFunction1
will only be available after it has been declared. utilFunction2
is hoisted to the top of the function, so can be used before it is defined.
function someGlobalFunction() { utilFunction1(); // Error: untilFunction1 is undefined :( utilFunction2(); // Works var utilFunction1 = function() { } function utilFunction2 () { } }
Unless they are trapped in a closure, both will cease to exist when someGlobalFunction
returns.
I prefer to use the method used to declare utilFunction2
, but it's up to you.
Declarations of the form utilFunction2
(which are called Function Declarations) have the benefit of being named (i.e. showing up as utilFunction2
) in your-favourite-debuggerTM, where as utilFunction1
(called Function Expressions) would just show up as an anonymous function.
For completeness, you also have the form;
var utilFunction3 = function utilFunction4() { // blah };
... which is called a named function expression, which has weird properties (and bugs (in older versions of IE)) of its own.
Yes, they are quite different:
Ex:
if (true) { function utilFunction() { return true; } } else { function utilFunction() { return false; } } utilFunction(); // returns false in IE, true everywhere else
IE takes the function scope issue to the extreme, effectively evaluating functions, even if there is no code path to them!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With