JavaScriptQuestion 03 of 36
Can you explain the scope of variables?
Answer out loud or in your head first, then compare.
Answer
Scope determines where a variable is accessible.
There is, among others:
- global scope,
- function scope,
- block scope.
JavaScript
const globalValue = 1;
function test() {
const functionValue = 2;
if (true) {
const blockValue = 3;
}
}globalValue is widely accessible.
functionValue exists only inside the function.
blockValue only inside the {} block.
let and const have block scope.
var has function scope.
Pitfall:
JavaScript
if (true) {
var x = 10;
}
console.log(x); // 10but:
JavaScript
if (true) {
let x = 10;
}
console.log(x); // ReferenceErrorHow did it go? Be honest — “Not yet” puts the question on your review list.