Course

Web Development
  • 1.1 Introduction to the Web
  • 2.1 HTML Basics
  • 2.2 Text & Content
  • 2.3 Layout & Grouping
  • 2.4 Lists & Tables
  • 2.5 Media & Embedding
  • 2.6 Forms
  • 2.7 Semantic HTML
  • 2.8 Accessibility & SEO
  • 3.1 CSS Introduction
  • 3.2 CSS Syntax
  • 3.3 CSS Selectors
  • 3.4 Typography
  • 3.5 Colors & Backgrounds
  • 3.6 Text Styling
  • 3.7 Box Model
  • 3.8 Units
  • 3.9 Display & Positioning
  • 3.10 Layout Systems
  • 3.11 Responsive Design
  • 3.12 Animations
  • 3.13 Modern CSS
  • 3.14 Performance & Accessibility
  • 3.15 Tailwind CSS Basics
  • 4.1 Introduction to JavaScript
  • 4.2 Variables & Scope
  • 4.3 Data Types
  • 4.4 Type Conversion
  • 4.5 Operators
  • 4.6 Control Flow
  • 4.7 Loops
  • 4.8 Functions
  • 4.9 Advanced Functions
  • 4.10 Objects & Arrays
  • 4.11 The this Keyword

4.2 Variables & Scope

Updated Jul 20, 2026

4.2 Variables & Scope

Updated Jul 20, 2026

Variables are containers used to store data in JavaScript.

Examples:

let name = "Samir";

let age = 21;

let isStudent = true;
name      → String
age       → Number
isStudent → Boolean

Variables allow us to store values and reuse them throughout a program.


What is a Variable?

A variable is a named storage location in memory.

Example:

let city = "Kathmandu";

Visual representation:

city
 ↓
"Kathmandu"

Why Use Variables?

Without variables:

console.log("Samir");
console.log("Samir");
console.log("Samir");

With variables:

let name = "Samir";

console.log(name);
console.log(name);
console.log(name);

Variables make code easier to read, reuse, and maintain.


Declaring Variables

JavaScript provides three ways to declare variables:

  • var
  • let
  • const

var

var is the original way to declare variables.

var name = "Samir";

Example:

var age = 21;

console.log(age);

Output:

21

Reassignment

Allowed:

var age = 21;

age = 22;

Redeclaration

Also allowed:

var name = "Samir";

var name = "John";

No error occurs.

Problem with var

var x = 10;

if (true) {

    var x = 20;

}

console.log(x);

Output:

20

The outer variable is overwritten because var is function-scoped, not block-scoped.


let

let was introduced in ES6 (2015).

Use it when the value may change.

let name = "Samir";

Example:

let age = 21;

console.log(age);

Reassignment

Allowed:

let age = 21;

age = 22;

Redeclaration

Not allowed.

let age = 21;

let age = 22;

Output:

SyntaxError

Example:

let score = 100;

score = 120;

console.log(score);

Output:

120

const

Use const for values that should not be reassigned.

const PI = 3.14159;

Example:

const country = "Nepal";

Reassignment

Not allowed.

const country = "Nepal";

country = "India";

Output:

TypeError

Redeclaration

Not allowed.

const country = "Nepal";

const country = "India";

Output:

SyntaxError

const with Objects

A const object cannot be reassigned, but its contents can be modified.

const user = {

    name: "Samir"

};

user.name = "John";

console.log(user.name);

Output:

John

The object changes, but the reference stays the same.


var vs let vs const

Feature var let const
Reassign ✅ ✅ ❌
Redeclare ✅ ❌ ❌
Block Scope ❌ ✅ ✅
Hoisted ✅ ✅ ✅
Modern Usage ❌ ✅ ✅

Which One Should You Use?

Modern JavaScript recommends:

const name = "Samir";

let age = 21;

General rule:

  • const → Default choice
  • let → When the value changes
  • var → Avoid in modern code

Hoisting

Hoisting is JavaScript's behavior of moving variable declarations to the top of their scope before execution.


Hoisting with var

console.log(name);

var name = "Samir";

Output:

undefined

JavaScript treats it like:

var name;

console.log(name);

name = "Samir";

Hoisting with let

console.log(name);

let name = "Samir";

Output:

ReferenceError

Hoisting with const

console.log(country);

const country = "Nepal";

Output:

ReferenceError

Temporal Dead Zone (TDZ)

The period between entering a scope and initializing a let or const variable is called the Temporal Dead Zone (TDZ).

Example:

{

    console.log(age);

    let age = 21;

}

Output:

ReferenceError

TDZ only applies to:

  • let
  • const

Variable Naming Rules

Valid names:

let name;

let firstName;

let age1;

let _user;

let $price;

Invalid names:

let 1name;

let first name;

let class;

let function;

Naming Convention

JavaScript uses camelCase.

Good:

let firstName;

let userAge;

let totalPrice;

Avoid:

let First_Name;

let TOTALPRICE;

Use meaningful variable names whenever possible.


Scope

Scope determines where a variable can be accessed.

There are three main types of scope:

  • Global Scope
  • Function Scope
  • Block Scope

Global Scope

Variables declared outside functions and blocks belong to the global scope.

let name = "Samir";

function greet() {

    console.log(name);

}

Output:

Samir

Visual:

Global Scope

├── name
├── function1
└── function2

Global variables are accessible everywhere.

Too many global variables can lead to:

  • Naming conflicts
  • Harder debugging
  • Unexpected changes

Function Scope

Variables declared inside a function are accessible only within that function.

function greet() {

    let message = "Hello";

    console.log(message);

}

greet();

Output:

Hello

Outside the function:

console.log(message);

Output:

ReferenceError

Visual:

greet()

└── message

var is also function-scoped.

function test() {

    var x = 10;

}

console.log(x);

Output:

ReferenceError

Block Scope

A block is created using braces:

{

}

Blocks appear in:

  • if
  • for
  • while
  • switch

Variables declared with let and const are block-scoped.

if (true) {

    let age = 21;

}

console.log(age);

Output:

ReferenceError

Another example:

{

    const country = "Nepal";

}

console.log(country);

Output:

ReferenceError

var and Block Scope

var ignores block scope.

if (true) {

    var age = 21;

}

console.log(age);

Output:

21

Using let:

if (true) {

    let age = 21;

}

console.log(age);

Output:

ReferenceError

Scope Chain

JavaScript searches for variables from the innermost scope outward.

Example:

let name = "Samir";

function greet() {

    console.log(name);

}

greet();

Search order:

Local Scope
      ↓
Parent Scope
      ↓
Global Scope

Shadowing

An inner variable can override an outer variable with the same name.

let name = "Samir";

function greet() {

    let name = "John";

    console.log(name);

}

greet();

Output:

John

Visual:

Global

└── name = Samir

Function

└── name = John

The inner scope takes priority.


Best Practices

Use const by default.

const PI = 3.14;

Use let when the value changes.

let count = 0;

count++;

Avoid var in modern JavaScript.

Use meaningful variable names.

Good:

let userName;

let totalPrice;

Avoid:

let x;

let abc;

Keep variables in the smallest scope possible.

if (true) {

    const age = 21;

}

This reduces bugs and makes code easier to maintain.


Key Takeaway

Modern JavaScript primarily uses:

const name = "Samir";

let age = 21;

Avoid:

var age = 21;

Remember:

const
      ↓
Default Choice

let
      ↓
When Value Changes

var
      ↓
Legacy Code

Scope determines where a variable can be accessed.

Global Scope
      ↓
Function Scope
      ↓
Block Scope

Understanding variables and scope is essential before learning functions, objects, loops, and the DOM.

4.1 Introduction to JavaScript4.3 Data Types