This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
I am reading some question where i find this code, it seems to be easy but i can't understand how this function:(function() {} ()) works.
Please help me to understand that how the value of var foo=6 and bar=9 is only consider in bar=bar+foo
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var foo = 6;
bar = 10;
(function () {
var foo = 5;
bar = 9;
}())
bar = bar + foo;
document.getElementById("demo").innerHTML = "Final value is " + bar;
</script>
</body>
</html>
That's a mix of some pretty bad variable usage, particularly the use of "undeclared" bar.
Basically, your global scope has 2 variables, foo & bar. At first they're initialized to 6 & 10 respectively. Then, a function is called that declares it own foo variable and sets that to 5. It also sets the global bar to 9. So now the global values are 6 & 9. The sum of these is then 15.
Since
var foo = 5;
has the var declaration, it's a local variable. The assignment has no effect on the foo variable outside the function. The global variable continues to have the value 6.
bar = 9;
doesn't have a var declaration, so it's just an assignment. Since the variable isn't declared locally within the function, this assigns the global variable, so the global variable now has the value 9.
When you add the two global variables afterward, you get 9 + 6 = 15.
Related
This question already has answers here:
Over how much of its enclosing scope does a (javascript) closure close?
(2 answers)
Closed 5 years ago.
We knew that
function foo () {
var x = 10;
var y = 20;
function bar () {
return x + 1;
}
bar(); // 11
}
The function bar create a closure, and save the reference of x.
But what about the variable y? Will the closure bar created hold its reference? I tried it in Chrome Dev Tools, and it shows only x in the [[Scopes]] field, without y. But I can not find any articles about that.
Does it means the closure creation will only pick what it need to save?
Scopes are chained together and it'll check with parent scope when reference cannot be find. This question is answered before and you can reference it here:
Scope Chain in Javascript
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 purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 8 years ago.
Is there a difference define variable in global scope between
var my_var;
and
my_var;
In global scope, there is no difference, unless you using it again: var my_var; will redeclare it, while my_var; will be simply useless expression.
There is a difference only when not in global context.
Ex1 (with var):
var x = 0;
(function(){
var x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 0
Ex2 (without var):
x = 0;
(function(){
x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 1
var is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.
Thus there is no difference in global scope, for it isn't contained in any other scope.
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