Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the var keyword and when should I use it (or omit it)?

NOTE: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.

What exactly is the function of the var keyword in JavaScript, and what is the difference between

var someNumber = 2; var someFunction = function() { doSomething; } var someObject = { } var someObject.someProperty = 5; 

and

someNumber = 2; someFunction = function() { doSomething; } someObject = { } someObject.someProperty = 5; 

?

When would you use either one, and why/what does it do?

like image 605
Alex Avatar asked Sep 24 '09 08:09

Alex


People also ask

What is the purpose of the var keyword?

The var keyword is used to declare variables in JavaScript. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. Storing a value in a variable is called variable initialization.

When should I use VAR in JavaScript?

Before ES6, the var keyword was used to declare a variable in JavaScript. The var keyword has been around since the inception of JavaScript, and it's what you will see in any pre ES6 code. Variables declared using the var keyword are either globally or functionally scoped, they do not support block-level scope.

What is the difference between declaring a variable with the keyword var and without the keyword var?

Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. Global variables are destroyed when you close the page. If you declare a variable, without using "var", the variable always becomes GLOBAL.

Is it necessary to use var keyword when declaring no yes?

Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a property of the global object). The difference is that a declared variable is a non-configurable property of the global object while an undeclared is configurable.


1 Answers

If you're in the global scope then there's not much difference. Read Kangax's answer for explanation

If you're in a function then var will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

// These are both globals var foo = 1; bar = 2;  function() {     var foo = 1; // Local     bar = 2;     // Global      // Execute an anonymous function     (function()     {         var wibble = 1; // Local         foo = 2; // Inherits from scope above (creating a closure)         moo = 3; // Global     }()) } 

If you're not doing an assignment then you need to use var:

var x; // Declare x 
like image 176
Greg Avatar answered Sep 23 '22 14:09

Greg