What Is the Purpose of the Var Keyword and When Should I Use It (Or Omit It)

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

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

What's the point of the var keyword?

Update: There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?

The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:

As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:

SomeGeneric<VeryLongTypename<NestedTypename>> thing = new   
SomeGeneric<VeryLongTypename<NestedTypename>>();

Verbose and error-prone, right? So now they let you do this:

var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();

By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.

When to use var in Javascript

When you use var , you are instantiating a variable in the current scope. This will also prevent access of variables named the same in higher scope, within the current scope.

In your first example, 'a' is being instantiated and set within the function scope. In your second example, 'a' is being set outside the function scope due to lack of var

With var:

var a = "A"
(function(){
var a = "B"
alert(a) //B
})()

alert(a); //A

Without var:

var a = "A";
(function(){
a = "B"
alert(a) //B
})()

alert(a) //B

What's advantage to use var in the variable declaration?

the key difference is if you don't use var keyword, your variable will be global, even if you defined it in some nested function.

var defines a scope for that variable. Using a global or not depends if you want to use your object across multiple scopes or not, but globals are strongly discouraged in favour of namespaces that reduce the global scope pollution.

difference between var keyword and without var

If var keyword is used within a function or other non-global scope then that variable's scope is not global .

If var keyword is not used before a variable name, then that variable's scope is global .

Is it necessary to use the keyword 'var' to declare a variable in Javascript

Using the keyword var ensures that your variable is properly scoped. If you do not use the keyword, then JavaScript will automatically create the variable as a global scope, which can cause issues later in the execution of your page.

name = 'Bic'; // implicitly global

function myFunc() {
var name = 'John'; // this variable is scoped here
console.log(name); // John
getName(); // Bic
}

function getName() {
console.log(name); //Bic
}

myFunc();
getName();

In the code above, I declared a global name, and a scoped name. Note, the global name lingers on after myFunc() has finished executing. name is a property of most HTML elements. In this particular answer, my declaration of name without the var keyword can have detrimental affects to a page's execution. The value of name gets thrown out of scope, and this can affect targeting elements, and other things. If you take a look at this Fiddle, and click Run again after it loads, you will notice it automatically opens a new tab. This is because the original value of name has been clobbered, and the page does not know where to truly open.

As a general rule, it is good to always declare variables with the var keyword, as this makes it easier to follow the scope of that variable, as avoids unforeseen issues they can cause.

As was noted by Pointy, the 'use strict' pragma (introduced in ECMAScript 5) actually prohibits the declaration of variables without the var keyword.

Do i need to use var variable or let variable in this example?

Don't use anything when you reset text

let text = prompt("write something");

while(text !== "exit")
{
text = prompt("write something"); // nothing, uses text in outer scope
}

console.log("end of program);

When you use 'let' in the while loop you are creating a separate variable
scoped to that statement block. When you use var, it is hoisted to the function, or to the global object if not in a function (or if you don't use var, let, or const and just attempt to use a variable without declaring it). Since the variables are in the same function (or global scope) using var, they refer to the same thing.

When using let, the variable is scoped to the block of code. So the 'text' variable inside the while statement block does not refer to the same 'text' variable declared outside that block and used in the while condition. Here's the example from the link:

let x = 1;

if (x === 1) {
let x = 2;

console.log(x);
// expected output: 2
}

console.log(x);
// expected output: 1

Is using 'var' to declare variables optional?

They mean different things.
If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.

This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.

javascript var or not var, what's the difference?

If you don't use it, it might be a global variable, or in IE's case, it'll just blow up.

There are cases you don't need it, for example if it's a parameter to the function you're in, it's already declared. Always use var in any other cases (other cases being: unless you're manipulating a variable that already exists). No matter what scope it needs to be defined at, explicitly define it there.



Related Topics



Leave a reply



Submit