window[name] equivalent to dynamically access const and let declarations - javascript

The old style JavaScript var declaration outside of a closure is global (top-level scope) and can be accessed in a browser from the window object. For example, the declaration var x = 3; can be accessed with window['x'].
How do you similarly access a const or let declaration given the name (string) of the declaration?
var x = 3;
const y = 7;
let z = 21;
console.log('x = ' + window['x']); //x = 3
console.log('y = ' + window['y']); //y = undefined
console.log('z = ' + window['z']); //z = undefined
For the above example, how do you get the values 7 and 21 for "y" and "z" instead of undefined?
Fiddle with the code:
https://jsfiddle.net/g78ah6we/
Edits (notes added for clarity):
1. While not typical, there are use cases, such as from within a library, that it's necessary to access a declaration based only on the name of the declaration.
2. Only read access is needed (none of the declarations will be modified).
3. The window object is mentioned just to show the old way, but this question is not actually about using the window object (or the global object).

Using indirect calls to eval
Accessing global const and let definitions can be done using an indirect call to eval. That is make eval the result of a comma separated expression or assign it to a variable first. If the syntactic access is not directly to the built-in eval function it's an indirect access, and indirect access executes in global scope.
You can also set global let variables by building script to perform the setting operation.
"use strict";
let myVar = "global variable myVar";
console.log( myVar);
(function myLibrary() {
const myVar = "local variable myVar";
const indirectEval = eval;
var varName = "myVar";
console.log( eval(varName)); // direct call uses local scope
console.log( indirectEval(varName)); // indirect call uses global scope
var result = "\"updated global variable even though shadowed\"";
var js = varName + '=' + result;
indirectEval(js);
// but trying to define a new let variable doesn't attach to global scope
var js2 ='let letVar2 = "let variable two"';
indirectEval( js2);
})();
console.log( myVar)
console.log( "letVar2: " + typeof letVar2);
What you can't do is add a let or const variable to global scope using an indirect call to eval: they are block level declarations and the code eval evaluates is considered a block - so the declarations are discarded when (indirect call to ) eval returns.
PS. This is a technical answer. And yes, I have heard that "eval is evil" before, one or three times.
For read access only using hard-coded variable name strings (to prevent code insertion) you could use the pattern:
(0,eval)("identifierString");
as for example:
var x = 3;
const y = 7;
let z = 21;
{
const y = "shadow"
let z = 42;
console.log('x = ' + (0,eval)('x')); //x = 3
console.log('y = ' + (0,eval)('y')); //y = 7
console.log('z = ' + (0,eval)('z')); //z = 21
}
Indirect vs direct calls to eval
A direct call to eval only obtains the values of global variables that have not been shadowed in function scope of the call. This may restrict choice of variable names, or where the call can be made from, within the library.
An indirect call executes in global scope and can obtain the value of global variables irrespective of name shadowing within the library.
Creating a new Function object from source text, and calling it, may provide be an alternative to using an indirect call to eval in a web page. However the difference is largely semantic rather than one being better than the other.
Issues
If the global variable name (var, let, const or class identifier) comes from user input it really should be checked for validity (not all that easy) or at least accessed within a try/catch block to trap used of undeclared identifiers or use of name declarations before initialization.
Personally I would recommend finding alternatives to using global variable name strings in general. Providing a static name space object on the library (e.g. myLibrary.data) and processing string values that are property names of the object, or including option object parameters in library calls, come to mind.

Both let and const are block scoped.
In contrast, the variable declarations without var keyword creates variables in the outermost functional scope bubble. In browsers, the outermost functional scope is controlled by the window object.
What the window object doesn't control is the outermost block scope.
If your code doesn't work without being able to access variables in the window[nn] pattern, there definitely is a design issue in it.

I've marked traktor53's answer as accepted and upvoted it because it contains the technical core of the solution.
In case it's helpful for anyone, here's a solution wrapped up into a function that prevents executing code in the declaration.
var x = 3;
const y = 7;
let z = 21;
const malware = 'alert("Game over.");';
function getDeclaration(name) {
var identifierPattern = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/;
var topLevelGet = (null, eval);
return identifierPattern.test(name) && topLevelGet('typeof ' + name) === 'number' ?
topLevelGet(name) : null;
}
console.log(getDeclaration('x')); //output: 3
console.log(getDeclaration('y')); //output: 7
console.log(getDeclaration('z')); //output: 21
console.log(getDeclaration('bogus')); //output: null
console.log(getDeclaration('malware')); //output: null
console.log(getDeclaration('if')); //EXCEPTION: unexpected keyword
Notes:
Be aware that the identifierPattern regex is very simplistic (does not handle all valid characters and trips up on reserved words... as traktor53 pointed out, "This is more complicated than you might think").
Change 'number' to 'object' or whatever is appropriate for your needs (for simplicity in the original question I used examples with numbers, but my real use case actually looks for objects).
Fiddle with the code:
https://jsfiddle.net/g78ah6we/6/

Related

how can i use destructuring inside a class in javascript [duplicate]

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?
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
There's a difference.
var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.
x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates x property on a global object (which is a top level object in a scope chain).
Now, notice that it doesn't declare a global variable, it creates a global property.
The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.
But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).
Hope it all makes sense : )
[Update 2010/12/16]
In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.
Saying it's the difference between "local and global" isn't entirely accurate.
It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.
/* global scope */
var local = true;
var global = true;
function outer() {
/* local scope */
var local = true;
var global = false;
/* nearest scope = outer */
local = !global;
function inner() {
/* nearest scope = outer */
local = false;
global = false;
/* nearest scope = undefined */
/* defaults to defining a global */
public = global;
}
}
When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:
with (window) {
//Your code
}
More info on with - MDN
Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.
The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.
Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.
A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.
EDIT:
After the critiques I received, I would like to emphasize the following:
var declares a variable in the current scope
The global scope is window
Not using var implicitly declares var in the global scope (window)
Declaring a variable in the global scope (window) using var is the same as omitting it.
Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
Always declare var explicitly because it's good practice
Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:
Any variable created without the var
keyword is created at the global scope
and is not garbage collected when the
function returns (because it doesn’t
go out of scope), presenting the
opportunity for a memory leak.
Here's quite a good example of how you can get caught out from not declaring local variables with var:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop
I would say it's better to use var in most situations.
Local variables are always faster than the variables in global scope.
If you do not use var to declare a variable, the variable will be in global scope.
For more information, you can search "scope chain JavaScript" in Google.
Don't use var!
var was the pre-ES6 way to declare a variable. We are now in the future, and you should be coding as such.
Use const and let
const should be used for ~95% of cases. It makes it so the variable reference can't change, thus array, object, and DOM node properties can change and should likely be const.
let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever write varName = beyond the initialization, use let.
Both have block level scoping, as expected in most other languages.
another difference
e.g
var a = a || [] ; // works
while
a = a || [] ; // a is undefined error.
Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.
Without var - global variable.
Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:
/* global: varname1, varname2... */
This is example code I have written for you to understand this concept:
var foo = 5;
bar = 2;
fooba = 3;
// Execute an anonymous function
(function() {
bar = 100; //overwrites global scope bar
var foo = 4; //a new foo variable is created in this' function's scope
var fooba = 900; //same as above
document.write(foo); //prints 4
document.write(bar); //prints 100
document.write(fooba); //prints 900
})();
document.write('<br/>');
document.write('<br/>');
document.write(foo); //prints 5
document.write(bar); //prints 100
document.write(fooba); //prints 3
#Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.
As you'd expect the following snippet outputs ["text"]:
function var_fun() {
let array = []
array.push('text')
return array
}
console.log(var_fun())
So does the following snippet (note the missing let before array):
function var_fun() {
array = []
array.push('text')
return array
}
console.log(var_fun())
Executing the data manipulation asynchronously still produces the same result with a single executor:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
var_fun().then(result => {console.log(result)})
But behaves differently with multiple ones:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
Using let however:
function var_fun() {
let array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.
If you run this code:
var local = true;
var global = true;
function test(){
var local = false;
var global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output will read as: false, false, true, true
Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:
var local = true;
var global = true;
function test(){
local = false;
global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output is false, false, false, false
This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.
I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:
See the script below in action here at jsfiddle
a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
function testVar1(){
c = 1;// Defined inside the function without var
var d = 1;// Defined inside the function with var
alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar1();
alert("Run the 1. function again...");
testVar1();
function testVar2(){
var d = 1;// Defined inside the function with var
alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar2();
alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);
Conclusion
No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.
Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:
someFunction() {
var a = some_value; /*a has local scope and it cannot be accessed when this
function is not active*/
b = a; /*here it places "var b" at top of script i.e. gives b global scope or
uses already defined global variable b */
}
Besides scopes issue, some folks also mention hoisting, but no one gave an example. Here's one for global scope:
console.log(noErrorCase);
var noErrorCase = "you will reach that point";
console.log(runTimeError);
runTimeError = "you won't reach that point";
Without using "var" variables can only define when set a value. In example:
my_var;
cannot work in global scope or any other scope. It should be with value like:
my_var = "value";
On the other hand you can define a vaiable like;
var my_var;
Its value is undefined ( Its value is not null and it is not equal to null interestingly.).
You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.
When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.
When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function.
(Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)
You may also want to look at hoisting in javascript

'setName' is not defined in functional component [duplicate]

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?
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
There's a difference.
var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.
x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates x property on a global object (which is a top level object in a scope chain).
Now, notice that it doesn't declare a global variable, it creates a global property.
The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.
But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).
Hope it all makes sense : )
[Update 2010/12/16]
In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.
Saying it's the difference between "local and global" isn't entirely accurate.
It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.
/* global scope */
var local = true;
var global = true;
function outer() {
/* local scope */
var local = true;
var global = false;
/* nearest scope = outer */
local = !global;
function inner() {
/* nearest scope = outer */
local = false;
global = false;
/* nearest scope = undefined */
/* defaults to defining a global */
public = global;
}
}
When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:
with (window) {
//Your code
}
More info on with - MDN
Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.
The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.
Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.
A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.
EDIT:
After the critiques I received, I would like to emphasize the following:
var declares a variable in the current scope
The global scope is window
Not using var implicitly declares var in the global scope (window)
Declaring a variable in the global scope (window) using var is the same as omitting it.
Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
Always declare var explicitly because it's good practice
Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:
Any variable created without the var
keyword is created at the global scope
and is not garbage collected when the
function returns (because it doesn’t
go out of scope), presenting the
opportunity for a memory leak.
Here's quite a good example of how you can get caught out from not declaring local variables with var:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop
I would say it's better to use var in most situations.
Local variables are always faster than the variables in global scope.
If you do not use var to declare a variable, the variable will be in global scope.
For more information, you can search "scope chain JavaScript" in Google.
Don't use var!
var was the pre-ES6 way to declare a variable. We are now in the future, and you should be coding as such.
Use const and let
const should be used for ~95% of cases. It makes it so the variable reference can't change, thus array, object, and DOM node properties can change and should likely be const.
let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever write varName = beyond the initialization, use let.
Both have block level scoping, as expected in most other languages.
another difference
e.g
var a = a || [] ; // works
while
a = a || [] ; // a is undefined error.
Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.
Without var - global variable.
Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:
/* global: varname1, varname2... */
This is example code I have written for you to understand this concept:
var foo = 5;
bar = 2;
fooba = 3;
// Execute an anonymous function
(function() {
bar = 100; //overwrites global scope bar
var foo = 4; //a new foo variable is created in this' function's scope
var fooba = 900; //same as above
document.write(foo); //prints 4
document.write(bar); //prints 100
document.write(fooba); //prints 900
})();
document.write('<br/>');
document.write('<br/>');
document.write(foo); //prints 5
document.write(bar); //prints 100
document.write(fooba); //prints 3
#Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.
As you'd expect the following snippet outputs ["text"]:
function var_fun() {
let array = []
array.push('text')
return array
}
console.log(var_fun())
So does the following snippet (note the missing let before array):
function var_fun() {
array = []
array.push('text')
return array
}
console.log(var_fun())
Executing the data manipulation asynchronously still produces the same result with a single executor:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
var_fun().then(result => {console.log(result)})
But behaves differently with multiple ones:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
Using let however:
function var_fun() {
let array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.
If you run this code:
var local = true;
var global = true;
function test(){
var local = false;
var global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output will read as: false, false, true, true
Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:
var local = true;
var global = true;
function test(){
local = false;
global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output is false, false, false, false
This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.
I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:
See the script below in action here at jsfiddle
a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
function testVar1(){
c = 1;// Defined inside the function without var
var d = 1;// Defined inside the function with var
alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar1();
alert("Run the 1. function again...");
testVar1();
function testVar2(){
var d = 1;// Defined inside the function with var
alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar2();
alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);
Conclusion
No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.
Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:
someFunction() {
var a = some_value; /*a has local scope and it cannot be accessed when this
function is not active*/
b = a; /*here it places "var b" at top of script i.e. gives b global scope or
uses already defined global variable b */
}
Besides scopes issue, some folks also mention hoisting, but no one gave an example. Here's one for global scope:
console.log(noErrorCase);
var noErrorCase = "you will reach that point";
console.log(runTimeError);
runTimeError = "you won't reach that point";
Without using "var" variables can only define when set a value. In example:
my_var;
cannot work in global scope or any other scope. It should be with value like:
my_var = "value";
On the other hand you can define a vaiable like;
var my_var;
Its value is undefined ( Its value is not null and it is not equal to null interestingly.).
You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.
When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.
When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function.
(Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)
You may also want to look at hoisting in javascript

Javascript: difference in execution of duplicate var and let variables within `execution context`? [duplicate]

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?
var is allow duplicate declaration
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
But let and const does not allow duplicate deceleration
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I saw something about that in here like,
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?
var
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.
let and const
Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Why Does it Matter?
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.
Unlike var, let is an ES2015 specification. The specification says:
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
This is to improve scoping over vanilla var.
why does const and let not allow duplicate declaration?
There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a compilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.
function checkLetDuplication() {
let i = 'function scope';
for ( let i = 0 ; i < 3 ; i++ )
{
console.log('(for statement scope): inside the for loop i, equals: ', i);
}
console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();
Assuming you want to know whether this behavior is as per spec, check this 13.3.2
Within the scope of any VariableEnvironment a common BindingIdentifier
may appear in more than one VariableDeclaration but those declarations
collective define only one variable.
let and const are the recent editions, while var is probably as old as Javascript itself.
In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?
var is allow duplicate declaration
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
But let and const does not allow duplicate deceleration
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I saw something about that in here like,
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?
var
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.
let and const
Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Why Does it Matter?
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.
Unlike var, let is an ES2015 specification. The specification says:
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
This is to improve scoping over vanilla var.
why does const and let not allow duplicate declaration?
There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a compilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.
function checkLetDuplication() {
let i = 'function scope';
for ( let i = 0 ; i < 3 ; i++ )
{
console.log('(for statement scope): inside the for loop i, equals: ', i);
}
console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();
Assuming you want to know whether this behavior is as per spec, check this 13.3.2
Within the scope of any VariableEnvironment a common BindingIdentifier
may appear in more than one VariableDeclaration but those declarations
collective define only one variable.
let and const are the recent editions, while var is probably as old as Javascript itself.
In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.

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?
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
There's a difference.
var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.
x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates x property on a global object (which is a top level object in a scope chain).
Now, notice that it doesn't declare a global variable, it creates a global property.
The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.
But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).
Hope it all makes sense : )
[Update 2010/12/16]
In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.
Saying it's the difference between "local and global" isn't entirely accurate.
It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.
/* global scope */
var local = true;
var global = true;
function outer() {
/* local scope */
var local = true;
var global = false;
/* nearest scope = outer */
local = !global;
function inner() {
/* nearest scope = outer */
local = false;
global = false;
/* nearest scope = undefined */
/* defaults to defining a global */
public = global;
}
}
When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:
with (window) {
//Your code
}
More info on with - MDN
Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.
The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.
Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.
A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.
EDIT:
After the critiques I received, I would like to emphasize the following:
var declares a variable in the current scope
The global scope is window
Not using var implicitly declares var in the global scope (window)
Declaring a variable in the global scope (window) using var is the same as omitting it.
Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
Always declare var explicitly because it's good practice
Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:
Any variable created without the var
keyword is created at the global scope
and is not garbage collected when the
function returns (because it doesn’t
go out of scope), presenting the
opportunity for a memory leak.
Here's quite a good example of how you can get caught out from not declaring local variables with var:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop
I would say it's better to use var in most situations.
Local variables are always faster than the variables in global scope.
If you do not use var to declare a variable, the variable will be in global scope.
For more information, you can search "scope chain JavaScript" in Google.
Don't use var!
var was the pre-ES6 way to declare a variable. We are now in the future, and you should be coding as such.
Use const and let
const should be used for ~95% of cases. It makes it so the variable reference can't change, thus array, object, and DOM node properties can change and should likely be const.
let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever write varName = beyond the initialization, use let.
Both have block level scoping, as expected in most other languages.
another difference
e.g
var a = a || [] ; // works
while
a = a || [] ; // a is undefined error.
Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.
Without var - global variable.
Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:
/* global: varname1, varname2... */
This is example code I have written for you to understand this concept:
var foo = 5;
bar = 2;
fooba = 3;
// Execute an anonymous function
(function() {
bar = 100; //overwrites global scope bar
var foo = 4; //a new foo variable is created in this' function's scope
var fooba = 900; //same as above
document.write(foo); //prints 4
document.write(bar); //prints 100
document.write(fooba); //prints 900
})();
document.write('<br/>');
document.write('<br/>');
document.write(foo); //prints 5
document.write(bar); //prints 100
document.write(fooba); //prints 3
#Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.
As you'd expect the following snippet outputs ["text"]:
function var_fun() {
let array = []
array.push('text')
return array
}
console.log(var_fun())
So does the following snippet (note the missing let before array):
function var_fun() {
array = []
array.push('text')
return array
}
console.log(var_fun())
Executing the data manipulation asynchronously still produces the same result with a single executor:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
var_fun().then(result => {console.log(result)})
But behaves differently with multiple ones:
function var_fun() {
array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
Using let however:
function var_fun() {
let array = [];
return new Promise(resolve => resolve()).then(() => {
array.push('text')
return array
})
}
[1,2,3].forEach(i => {
var_fun().then(result => {console.log(result)})
})
As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.
If you run this code:
var local = true;
var global = true;
function test(){
var local = false;
var global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output will read as: false, false, true, true
Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:
var local = true;
var global = true;
function test(){
local = false;
global = false;
console.log(local)
console.log(global)
}
test();
console.log(local);
console.log(global);
The output is false, false, false, false
This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.
I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:
See the script below in action here at jsfiddle
a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
function testVar1(){
c = 1;// Defined inside the function without var
var d = 1;// Defined inside the function with var
alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar1();
alert("Run the 1. function again...");
testVar1();
function testVar2(){
var d = 1;// Defined inside the function with var
alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar2();
alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);
Conclusion
No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.
Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:
someFunction() {
var a = some_value; /*a has local scope and it cannot be accessed when this
function is not active*/
b = a; /*here it places "var b" at top of script i.e. gives b global scope or
uses already defined global variable b */
}
Besides scopes issue, some folks also mention hoisting, but no one gave an example. Here's one for global scope:
console.log(noErrorCase);
var noErrorCase = "you will reach that point";
console.log(runTimeError);
runTimeError = "you won't reach that point";
Without using "var" variables can only define when set a value. In example:
my_var;
cannot work in global scope or any other scope. It should be with value like:
my_var = "value";
On the other hand you can define a vaiable like;
var my_var;
Its value is undefined ( Its value is not null and it is not equal to null interestingly.).
You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.
When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.
When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function.
(Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)
You may also want to look at hoisting in javascript

Categories