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.
Related
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();
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.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.
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
This question already has answers here:
Understanding JavaScript function scoping
(4 answers)
Closed 9 years ago.
I am new to js and playing around with simple code. When I run the following code
var x=5;
function sum(){
alert(x);
var x=10;
alert(x);
}
sum();
I am getting the alert as "undefined" and 10.
But when I am running the following code,
var x=5;
function sum(){
alert(x);
x=10;
alert(x);
}
sum();
I get the alerts as "5" and "10"
Can someone please explain what is happening?
Note: sorry for giving the same code twice. Have changed now :).
Thanks
The function you have provided is being affected by hoisting. When you declare a local variable it is hoisted to the top of the function, which leaves x undefined.
When the interpreter encounters the function it hoists the local variable x like:
var x=5;
function sum(){
var x;
alert(x); //local x is in scope and undefined
x=10;
alert(x);
}
sum();
In the second function you provide, no hoisting occurs because there is only one global variable x and the function alerts the global variable with its assigned value.
So the main difference between the two functions is that the first function uses two variables, a global variable and a local variable, while the second function uses one global variable. In the first function the local variable is hoisted to the top of the function causing it to output undefined for the first alert.