Quiz

Explain the concept of scope in JavaScript

Topics
JavaScript
Edit on GitHub

TL;DR

In JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces {}) it is declared.

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

Scope in JavaScript

Global scope

Variables declared outside any function or block have global scope. They are accessible from anywhere in the code.

var globalVar = 'I am global';
function myFunction() {
console.log(globalVar); // Accessible here
}
console.log(globalVar); // Accessible here

Function scope

Variables declared within a function are in function scope. They are accessible only within that function.

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

Block scope

Variables declared with let or const within a block (e.g., within curly braces {}) have block scope. They are accessible only within that block.

if (true) {
let blockVar = 'I am in a block';
console.log(blockVar); // Accessible here
}
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined

Lexical scope

JavaScript uses lexical scoping, meaning that the scope of a variable is determined by its location within the source code. Nested functions have access to variables declared in their outer scope.

function outerFunction() {
var outerVar = 'I am outside';
function innerFunction() {
console.log(outerVar); // Accessible here
}
innerFunction();
}
outerFunction();

Further reading

Edit on GitHub