This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
My question is why is a variable (when using var keyword) accessible outside the if statement block, but not outside the function block? Consider this code:
let age = 30;
if (true){
let age = 40
console.log('inside', age) //logs inside, 40//
var name = 'shaun'
}
console.log('outside if loop', age, name) //logs outside if loop, 30, shaun //
function test (){
var xyz = 'ashley';
console.log(xyz)
}
test ()
console.log('outside function', xyz) //throws an error//
Thank you for your time. Any insights would be appreciated!
Because of the current context of execution. The context in which values and expressions are "visible" or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
A function serves as a closure in JavaScript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.
Also ES6 does have block scope for variable definitions with the let and const keywords but not with var.
Here is an article on Wikipedia about Scope.
Related
This question already has answers here:
why don't const and let statements get defined on the window object [duplicate]
(2 answers)
Closed 3 years ago.
Consider the code below which I am running in my chrome browser console:
var x = "hello";
let foo = function(){
console.log("hi");
};
console.log(x); // hello
console.log(foo()); //hi
console.log(window.x); // hello
console.log(window.foo()); // Error
If I had used var foo =... instead of let foo = .. then this would have worked. Why ?
This is by design:
let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below).
Just like const the let does not create properties of the window
object when declared globally (in the top-most scope).
This question already has answers here:
JavaScript loop variable scope
(5 answers)
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
My code was compiled to the following, and it works, but I do not know why. The variable that references the incrementing value is not included as an argument in the for loop.
var _loop2 = function _loop2() {
var p = document.createElement('p');
p.setAttribute('class', 'location__result');
p.setAttribute('data-id', response.features[i].id);
p.setAttribute('data-center', response.features[i].center);
p.textContent = response.features[i].place_name;
p.addEventListener('click', function () {
endingInput.value = p.textContent;
endingResults.style.display = "none";
placeIconAndZoom(p, position);
});
endingResults.appendChild(p);
};
for (var i = 0, length = response.features.length; i < length; i++) {
_loop2();
}
A function (x) declared inside another function (y) has access to all variables in the scope of the x (unless they are masked by another variable of the same name).
y can also be the global or module scope rather than a function per se.
var i = "example";
function x() {
console.log(i);
}
x();
This is the classic case of why const and let were introduced in ES6
var has a function level scope. This differs to const and let in terms of scoping, where the variable defined in var can be accessible anywhere in hits function declaration.
In your case, we declare var i inside the for loop (the function level scope), and your for loop is calling your _loop2 function. Since _loop2 is part of the for loops function scope, you're able to access that variable.
This SO answer can explain it a million times better than I can:
What's the difference between using "let" and "var"?
You can fix this by either adding: use 'strict' ontop of your script file, but a much better way is to avoid using var all together (unless there is a special circumstance) and switch it to let
This question already has answers here:
How do JavaScript closures work?
(86 answers)
How is a closure different from a callback?
(9 answers)
Closed 5 years ago.
From every definition I have looked up, closure is when a function is created or declared from within another function. Examples are plentiful across blogs and websites of this happening. But what about when the function is declared outside of another function, but called then called from within a function? For example:
const add = (x,y) => {
return x + y;
};
const double = num => {
return add(num,num)
};
let a = double(6);/*?*/
Does add(num, num) create closure? If so, please help me understand why.
Closures are a product of lexical scope.
A closure is the combination of a function and the lexical environment
within which that function was declared.
You must define a function within another one to create a closure.
What you do in your example is simply call a function that calls another and uses its return value. At no point can the double function access the scope of the add function: their scopes are distinct.
Here is a classical example of JavaScript closure
var makeAdder = function(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In both cases, the functions returned by makeAdder, "remember" the outer scope in which the were created (the scope created by the makeAdder function).
Anything that was in scope of the outer function was also in scope for the inner function, and it remains so when the inner function is returned.
This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
Closed 5 years ago.
let pages =100;
let pageFunction=()=>{
console.log(pages);
const pages = "20";
//console.log(pages);
}
pageFunction();
Output:
Uncaught ReferenceError: pages is not defined
at pageF (:3:13)
at :1:1
According to Mozilla "The let statement declares a block scope local variable, optionally initializing it to a value." Also "At the top level of programs and functions, let, unlike var, does not create a property on the global object."
See
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let for more information.
This means that in the code you gave you effectively create an implicit global variable pages, as let pages is not really global, but restricted to the scope it is in.
This question already has answers here:
javascript variable scope in the IF statement
(5 answers)
Closed 6 years ago.
I am currently reading through some javascript tutorials and I came upon this bit of example code from here: http://www.w3schools.com/js/js_if_else.asp
if (hour < 18) {
greeting = "Good day";
}
In this example, the greeting variable is not prefixed with a var statement. Now I looked up what this means, and my understanding is that it causes java script to look to a higher scope, if no variable is discovered by the global scope it creates it.
So is this tutorial doing this because the if statement's block is a local environment? If so does that mean that if I were to have some code that looked like this:
if (condition){var x=10};
else {var x=5};
then there would still be no global variable x for me to call?
In JavaScript (ES5), an if statement does not create a local scope when declaring with var. Local scope is created with a function.
W3Schools is notorious for using bad practices in their code samples, and you've found one example of this. They are creating a globally-scoped variable.
Blocks will only create a local scope for variables declared with the new let keyword. If you're using an older version of JavaScript, or if you're using the var keyword, then the variable is scoped to the innermost function that the variable is declared in.
Variables declared via var outside of any function are scoped to the window (global) scope.
{
var x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
In the above snippet, if you replaced var with let, it would produce an error because x is undefined.
{
let x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
You would be able to get the value of x outside of the if..else. This is due to JavaScript having function scope rather than block. I created a JSFiddle of your example, which can be found at https://jsfiddle.net/h4gjb8mt/
Example:
var condition = true;
if (condition) {
var x=10;
}
else {
var x=5;
}
console.log(x);