What is scope in JavaScript and what types exist?
Show answer — try answering out loud first
Scope is the region of the code where a variable is accessible. There is global scope, function scope and block scope. var uses function scope; let and const use block scope.
Scope defines "from where you can see" a variable.
- Global scope: variables declared outside of any function. They are visible everywhere.
- Function scope: variables declared inside a function. They only exist within it.
- Block scope: variables declared with
letorconstinside a block{ }(anif, afor, etc.). They only exist within that block.
An inner function can access the variables of the functions that contain it (this is called the scope chain). But not the other way around: what is inside is not visible from outside.
const global = "soy global";
function externa() {
const deLaFuncion = "solo dentro de externa";
console.log(global); // OK: it can see the global
if (true) {
let delBloque = "solo dentro del if";
console.log(deLaFuncion); // OK: it sees the function's variable
}
// console.log(delBloque); // Error: outside its block
}
externa();
// console.log(deLaFuncion); // Error: outside its function
// The scope chain: the inner one sees the outer one
function padre() {
const mensaje = "hola";
function hijo() {
console.log(mensaje); // OK: the child sees the parent's variable
}
hijo();
}
padre(); // "hola"
Thinking that a variable declared with var inside an if or a for only lives in that block. It does not: var ignores blocks and its scope is the entire function. Only let and const respect block scope.
"Scope is the region where a variable is accessible. We have global, function and block scope.
varhas function scope, whileletandconsthave block scope, meaning they only exist within the braces where they are declared. In addition, inner functions can access the variables of outer ones thanks to the scope chain, but not the other way around."
What does this print and why?
function prueba() {
if (true) {
var a = 1;
let b = 2;
}
console.log(a);
console.log(b);
}
prueba();
See answer
It prints 1 and then throws an error b is not defined. var a has function scope, so it survives outside the if. let b has block scope and does not exist outside the if.