Quiz

Explain the difference between global scope, function scope, and block scope

Topics
JavaScript
在GitHub上编辑

TL;DR

Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within {}) they are declared in.

var globalVar = "I'm global"; // Global scope
function myFunction() {
var functionVar = "I'm in a function"; // Function scope
if (true) {
let blockVar = "I'm in a block"; // Block scope
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
}

Global scope, function scope, and block scope

Global scope

Variables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the window object.

var globalVar = "I'm global";
function checkGlobal() {
console.log(globalVar); // Accessible here
}
checkGlobal(); // Output: "I'm global"
console.log(globalVar); // Output: "I'm global"

Function scope

Variables declared within a function are only accessible within that function. This is true for variables declared using var, let, or const.

function myFunction() {
var functionVar = "I'm in a function";
console.log(functionVar); // Accessible here
}
myFunction(); // Output: "I'm in a function"
// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined

Block scope

Variables declared with let or const within a block (e.g., within {}) are only accessible within that block. This is not true for var, which is function-scoped.

if (true) {
let blockVar = "I'm in a block";
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
if (true) {
var blockVarVar = "I'm in a block but declared with var";
console.log(blockVarVar); // Accessible here
}
console.log(blockVarVar); // Output: "I'm in a block but declared with var"

Further reading

在GitHub上编辑