variables scope confusion in javascript [duplicate] - javascript

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 9 years ago.
I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo gets gets value 3 in second log. even when foo is declared by using var in if statement. shouldn't the foo declared in if will have a new instance as it gets in bar()??

if does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {} creates a scope block.

There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if statement doesn't have a scope of its own, so the variable inside the if statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var keyword inside the if statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1

Related

JavaScript: understanding scope chain [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 3 years ago.
What is the scope chain in following code snippet -
var name = 'John';
function foo() {
if (false) {
var name = 'James';
}
console.log(name);
}
foo();
I got couple of queries regarding this -
Why the logger in function foo is printing undefined even when the variable
is available in global scope? Is it due to the fact that same variable
is re-declared in conditional falsy block and so the global variable is
getting removed from the scope?
Also if we replace the variable declaration under if statement inside function foo from var to let, the logger inside the function foo prints name from global scope. How this is working?
Yes this is because the variables declared with var have function scope and they are hoisted to the top of the function. It logs undefined due to hoisting.
Variables declared with let have block scope so until the if block is not executed the variable name is not declared.
Even if you change it with if(true) it will not work because the variable will only be available inside the block. {} not outside.
Here is the example how let works.
if(true){
let x = 3
}
console.log(x);
If you redeclare variable with var, it has the scope in the whole function. If you do it with let instead of var, it will be available only in the if scope.
var name = 'John';
function foo() {
if (false) {
let name = 'James';
}
console.log(name);
}
foo();

Difference between local and global variables in javascript? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 6 years ago.
I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.
For example :
function myfunction() {
x = 10;
var y = 10;
}
what is the difference between these both?
function myact() {
x = 20;
var y = 10;
console.log(x);
console.log(y);
}
myact();
console.log(x);
//y not available here
var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.
JS Docs says:
The scope of a variable declared with var is its current execution
context, which is either the enclosing function or, for variables
declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a
global variable (it becomes a property of the global object) when the
assignment is executed.

How exactly works the Javascript variable scope? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
I am pretty new in JavaScript and I have some doubts related to the variable scope.
So I tryed to do this example:
function outer() {
alert("INTO outer()");
var val1 = 1;
inner();
alert(val2);
}
function inner() {
alert("INTO inner()");
val2 = 2;
}
outer();
In this simple example the outer() function is perform, in this function I call the inner() function that declare and initializes the val2 variable. Then come back to the outer() function and from here I access and print the val2 value.
So it seam to me that in Javascript I can access to the variable defined in the inner function from the outer function but I can't access to the variable declared in the outer function from the inner function.
Is it true? If it is true why this choose?
It is true..The use of var in function 'outer' makes val1 local variable whereas val2 of function 'inner' has global scope since the keyword var is not used.
The declaration in your "inner" function is missing the var keyword. That makes val2 a global symbol.

Does javascript implement lexical scoping? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 8 years ago.
Why does this return 2 instead of 1? Seems the second "var" is silently ignored.
function foo()
{
var local = 1;
{
var local = 2;
}
return local;
}
foo()
/*
2
*/
In javascript there is only function level scope and global scope. you cannot create a block scope and it adds no special meaning and does not create any scope.
And this is how your code ends up
function foo()
{
var local = 1;
local = 2;
return local;
}
foo();
In ES6 you can create block level scopes with the help of Let. ES6 is not supported yet. more on that here
From the MDN :
JavaScript does not have block statement scope; rather, a variable
declared within a block is local to the function (or global scope)
that the block resides within.
The scope of a variable in JavaScript is the whole function in which it is declared (or the global scope), so you only have one variable local here.
Your code is equivalent to
function foo()
{
var local;
local = 1;
{
local = 2;
}
return local;
}
foo()
Note that ES6 (the new norm of JavaScript) does introduce a lexical scoping with let but it's not yet really available.

JavaScript local and global variable confusion [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Variable: local scope, global scope or is it the JavaScript engine?
(3 answers)
Closed 9 years ago.
I am new to JavaScript and I was doing some practices on local and global variable scopes. Following is my code(fiddle):
var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();
When the first alert is called, it is showing myname as undefined. So my confusion is why I am not able to access a global instance of myname and if I don't define myname within the function then it will work fine.
In JavaScript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:
var myname = "initial"
function c(){
var myname;
// Alerts undefined
alert(myname);
myname = "changed";
// Alerts changed
alert(myname);
}
c();
This is called hoisting.
Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.
It is not replacing the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them.
Try this:
var myname = "initial";
function c() {
alert(myname);
myname = "changed";
alert(myname);
}
c();

Categories