Define a local function in JavaScript: use var or not?

When a local (internal) function is declared in JavaScript, there are two options:

Declared with the var keyword assigning to a variable:

 (function() { var innerFunction1 = function() { ... }; innerFunction1(); }()); 

Declaring only using the function keyword without assigning a variable:

 (function() { function innerFunction2() { ... }; innerFunction2(); }()); 

I see one advantage of the second: a function can be declared below the code that calls it, so it’s easier to separate private functions from actually executed code.

Which one is better and why ?

+50
javascript function closures declaration
May 08 '13 at 11:51
source share
11 answers

There are actually 3 ways to declare a function:

  • Function declaration : A function declaration defines a named function variable without the need for variable assignment. Function declarations occur as standalone constructs and cannot be nested inside non-functional blocks. ex: function innerFunction1 () { };

  • Function expression :: An Expression function defines a function as part of the syntax of a larger expression (usually the purpose of a variable). Functions defined using function expressions can be called or anonymous:

    but. Using an anonymous function - var innerFunction1 = function() { };

    b. Using the named function - var innerFunction1 = function myInnerFunction () { };

  • Function constructor : The function constructor dynamically defines a function using the Function () constructor. Note that the body of the function is passed to the function as a string argument. var innerFunction1 = new Function (arg1, arg2, ... argN, functionBody)

The third method is not recommended, as passing the body of the function as a string can interfere with some JS engine optimization and is error prone.

The differences between a function declaration and a function expression are subtle, and you should choose the one that best suits your requirements.

I use a function expression where I need

  • singleton function or
  • to determine which function to use programmatically (using the function name of the function).

Some differences between function declaration and function expression:

  • Functional expressions allow you to assign different functions to the same variable at different points.
  • The function defined by the function declaration can be used before the function declaration (or mainly anywhere in the current area), while the function defined by the function expression can be used only after the point is defined.

Click here to read a detailed comparison of a function declaration vs Function Expression vs Function Constructor @MDN p>

Note. A function declaration can easily be turned into a function expression by assigning it to the var variable.

 function foo() {} alert(foo); // alerted string contains function name "foo" var bar = foo; alert(bar); // alerted string still contains function name "foo" 

More details:

+40
May 14 '13 at 17:38
source share

Two entries are functionally equivalent.

It can be assumed, that:

 function a() {} function b() {} 

interpreted as:

 var a, b; a = function a() {}; b = function b() {}; 

That is why you do not need to declare (do not define!) Before use. You can reassign functions after you define them, just like with a variable. Functions are raised just like variables, because they are variables (mind = blown? Good!).




Announces Up-Use

 function a() { b(); } // using b before it declared? function b() {} 

becomes:

 var a, b; a = function a() { b(); }; // nope! b is declared, we're good b = function b() {}; 



Function override

 function a() { alert("a"); } a = function b() { alert("b"); }; // that weird! 

becomes:

 var a; a = function a() { alert("a"); }; a = function b() { alert("b"); }; // oh, that looks normal 



Declare vs define

Declare: var x . In English: "I will use the variable x ".

Define: x = 5 . In English, "Variable x now has a value of 5 ".

Requires declaration and use in "use strict" . Define-up-use is not required. If your variables are defined at runtime, you're good.

So, var x = 5 is a declaration and definition, as is function a() {} .

Be careful if the naming functions do not overlap an existing variable:

 var a = function () { alert("a"); }; var b = function a() { alert("b"); }; a(); // prints "b" 

Lint tools will go for it.




When to use this notation?

I would recommend using the notation of a function expression ( var a = function () {} ) only if you later reassign the value of a . The function expression then signals to the reader that a will be reassigned and that he intends.

Another (secondary) argument to denote a function expression is a Lint tool, such as JSLint, which may require you to declare (not define!) Your functions before using them. If you have functions with a recursive definition, i.e. a calls b and b calls a , you cannot declare one by one using function declaration notation.

Edit notes: I revised the anonymous features a bit. It may be useful to call anonymous functions when you look at the stack. A named function will provide more context so that it is not registered as "anonymous."

+7
May 18 '13 at 2:05
source share

The difference is that the function with the VAR is determined at runtime ,

whereas a function () without a VAR is defined during parsing for a script block.

This is the only significant difference.

So, the user will make a decision based on the requirements that will be used and which meets the requirement.

+3
May 17 '13 at 6:32
source share

There is no difference in the conclusions. Both of them can still be called, and both can have access to their prototype by name.

There are only two real differences.

1) Readability and preferences

Some people find one way easier to read than others, and they, in turn, base their agreement on this style. The following agreement is important.

2) Small space savings

With the fact that minimization is becoming more and more relevant for scripts, you can see how it can be beneficial to use the second approach, since it does not require the use of var or = , which will save basically insignificant 4 space characters in a reduced script.




Summary

It all depends on preferences. What's better? You tell me. Personally, I will use var if I intend to make an object out of it using new , and then write it in the first letter, for example Person. Otherwise, I lean towards camelCase and omit the use of var .

+2
May 14 '13 at 23:38
source share
  • var without function name

    • it's better if you learn variable declarations: especially when they are declared.


  • A function with a name without var :

    • implies declaring a so-called variable at the beginning of the current region and may prevent some errors,
    • but : declaring a function this way using the closure variable declared with var will fail if that function is called before the closure variable is declared. So you must know what you are doing.


  • Function with or without var

    • suitable for class declaration,
    • and for profiling, for example, the Chrome dev profiling tool will be more explicit if the functions are not anonymous: they will have an explicit name and you will find out where the slow part of your code is.


  • Function named and with var

    • is a way to have a function as a named scope without having a declared variable as a closure
    • while maintaining the order in which the variable is declared.
+1
May 12 '13 at
source share

Local declarations should always use var.

Well, I would say that at first it is better, since this is a local area, and the memory can be cleared after the character is no longer used.

There is also a note on the google javascript style guide stating that the second form is not part of the standard and should therefore not be used.

Function declarations inside blocks

Do not do this:

if (x) {function foo () {}} Although most scripts support engines, declaring functions inside blocks is not part of ECMAScript (see ECMA-262, clauses 13 and 14). Worse implementations are incompatible with each other and with future EcmaScript offerings. Only ECMAScript allows the declaration of functions in the list of root script or function statements. Instead, use a variable initialized with the Expression function to define the function inside the block:

if (x) {

var foo = function () {}

}

Source http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml .

+1
May 17 '13 at 2:30
source share

Agree with @MarmiK. Also the difference between the two methods is the area. While a function declaration assigns a default local scope, the scope of the function assigned to the variable depends on the scope of the variable.

 var a; (function() { var innerFunction1 = function() { ... };//local scope a=innerFunction1;//assigning to a global variable }()); 

global access available. Go with the function declaration if you don't need to change the scope. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope

EDIT:

 var a; (function() { function innerFunction1() { ... };//local scope a=innerFunction1;//It works too(Don't know why it should though) }()); 

So, as pointed out by @Frits, there seems to be no advantage in using one type over another.

+1
May 17 '13 at 8:22
source share

Zakas says that "as long as you always define functions before using them, you are free to use function declarations or function expressions."

This means that if your code is changed tomorrow by another person that you don’t know some day, and this is a big project that the developer cannot find where the function is declared, you must use the function declaration (i means function x () {}), or if you declare functions first, you can use expressions.

0
May 15 '13 at 6:45
source share

I think that everyone who starts programming in JavaScript will sooner or later ask themselves a question. I would reformulate your question:

Should I use (prefer to use) a function declaration (function statement) or function expression (var version)?

In most cases, you can write good JavaScript code using only one of the constructs. It is clear that there are some important differences in semantics, but I want to emphasize that, in my opinion, the answer to the question is mainly the answer about the style of the program . Therefore, I would answer that in the most real cases the choice of the question of taste .

People who prefer to use a function operator use it mostly not when they need to define a readonly function variable, and not why they do not want to declare it before using it. In my opinion, he uses it mainly because he likes the shape.

So, I think that there is no objectively correct answer to your question. The choice is subjective. Therefore, I write in my answer which design I personally prefer and in which situations.

My first languages ​​were Pascal, C, Fortran, C ++, etc. I used C # now. So when I started writing JavaScript programs, at first I used my existing style of writing programs from other languages. Later, I changed the style of my JavaScript code to match the specifics of the language.

I personally prefer to use a function expression style, and I declare all functions in the first expression of an external function. I find that the form, which is mostly understood by JavaScript semantics, where the function name is a variable, contains the value of the function. The function name obeys hoisting , like any other variable. For example, my code looks below

 (function() { "use strict"; var myFunc1 = function (x) { // body where I can use x and this alert("x=" + x + ", this.foo=" + this.foo); }, localVar1 = {foo: "bar"}; myFunc1.call(localVar1, 1); }()); 

I use the function operator very rarely, and only if I declare the class constructor as follows:

 (function() { "use strict"; function MyClass(x) { // the code of constructor this.abc = x; } var myInstance = new MyClass("xyz"); alert(myInstance.abc); }()); 

I try never to use the third form:

 (function() { "use strict"; var myFunc1 = function myFunc2(x) { ... }; ... }()); 

where myFunc2 declared in addition to myFunc1 . The implementation of this form depends on the web browser. It makes sense, probably in the case of using recursive functions.

0
May 15, '13 at 13:20
source share

Javascript function definition

As mentioned by Vega, there are 3 ways to define a function:

  • function constructor
  • Function Declaration
  • function expression



Constructor Cons of Function:

Function constructors require a function body as a string, which:

  • may interfere with JS engine optimization
  • makes the syntax incredibly difficult to write: special characters and some other insanity must be avoided, see below

    var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();

    foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.

Feature Announcement:

It can be called before declaring a function, this really introduces complexity:

  • If you are performing a new function declaration inside another function, how can you achieve your new function? see Ready jQuery document and function area
  • Why should a function declaration be invokable before it is defined when the rest of the javascript behaves differently?
  • Did you know that in the background "a function declaration also creates a variable with the same name as the function name" !?
  • What happens if a variable with the same name as the function declaration is defined before (or after)?
  • Can my function definition still be called when I surround it with two brackets? http://jsbin.com/makipuxaje/1/edit?js,console vs http://jsbin.com/demecidoqu/1/edit?js,console vs http://jsbin.com/xikufakuwo/1/edit? js console
  • It is very easy to convert function declarations into function expressions, intentionally ... or by mistake, do you understand the consequences? see What does an exclamation mark do before a function? as well as JavaScript plus the sign before the function name
  • Javascript scope and rise
  • Why do my JavaScript function names collide?

Pluses of function expression:

Function expressions are simpler:

  • you "just know" which variable is assigned
  • you cannot call / refer to the variable that the function is assigned to before defining it, which is consistent behavior with other javascript definitions



More on: Converting Function Declarations to Function Expressions

Danger: as mentioned in the "Lack of function declaration", this can lead to many problems, below is more detailed information about this.

It is very easy to convert function declarations to function expressions.

"A function declaration ceases to be one when it: becomes part of the expression, is no longer the" source element "of the function or the script itself." The source element "is not nested in a script or function body https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Examples_2

function operators

β€œbe lifted, this means that no matter where the function is located, it moves to the top of the area in which it is defined. This weakens the requirement that functions be declared before use, which I think results in inaccuracy and also prohibits the use of function statements in if statements. It turns out that most browsers allow function statements in if statements, but they differ in how they should be interpreted, which creates portability problems. " - from book: Javascript Good Parts




More about function expressions

Syntax such as:

  var varName = function [name]([param] [, param] [..., param]) { /* function expression */ statements } 

Notes on [name] (immediately after the "function" in the syntax):

  • The name function may be omitted , in which case the function will become known as an anonymous function .
  • "The function name cannot be changed, and the variable assigned to the function can be reassigned."
  • "The name of the function can only be used inside the body of the function.", You can use this function to make the function call itself recursively.

Then, using [name] , you can do strange / funny things like below. Please note: I do not recommend this if you are new to function definitions.

 var count = 0; var varName = function funcName() { /* function expression */ console.log('count is: ' + count ); if(count<1){ count++; funcName(); /* calls function funcName another time */ } }; varName(); // invokes function funcName via variable varName funcName(); // throws an error as funcName is not reachable 

see live demo at jsbin.com/gijamepesu/1/edit?js,console

A typical implementation and use will be as shown below.

  var myCoolFunc = function ( username, firstName, lastName ) { /* function expression */ console.log('user ' + username + ' has the real full name ' + firstName + ' ' + lastName); } myCoolFunc(); 

One more note: functional expressions can be called right away, but declarations of vs-functions cannot. This function is used in IIFE, more about What is the purpose of wrapping all Javascript files in anonymous functions like "(function () {...}) ()"?




Resources

0
Nov 05 '14 at 16:50
source share

Short answer: It does not matter in the code, but you have to put var to make it more readable.

Long answer: Local variables in JavaScript, like global variables in JavaScript, can be defined with or without var . Therefore, the program function will not interfere with the absence or presence of the word var . Since reading code with var easier, it is recommended that before they are declared, before they are declared, add var . But if you want it to be unreadable, you should not put var before the variable definition.

-3
May 12 '13 at 1:47
source share



All Articles