Introduction to JavaScript

Scope and Closures in JavaScript

Scope in JavaScript

Scope refers to the context in which variables are declared and can be accessed. JavaScript has function and block scope (introduced with let and const).

Function Scope

Variables declared with var are function-scoped, meaning they are accessible within the function where they are defined.

function foo() {

var x = 10;

console.log(x);

}

foo(); // Output: 10

console.log(x); // Error: 'x' is not defined

Block Scope

Variables declared with let and const are block-scoped, meaning they are limited to the block in which they are defined (e.g., inside loops or conditionals).

if (true) {

let y = 5;

console.log(y);

}

console.log(y); // Error: 'y' is not defined

Closures in JavaScript

Closures are functions that remember the environment in which they were created, including variables from their outer scopes.

function outerFunction() {

let outerVar = 'I am from outerFunction';

 function innerFunction() {

   console.log(outerVar);

 }

 return innerFunction;

}

let innerFunc = outerFunction();

innerFunc(); // Output: I am from outerFunction

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board