Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 2: Variables, Constants & Memory Management

1. The Variable Lifecycle

In JavaScript, a variable goes through three stages:

  1. Declaration: let x; (The engine registers the name).
  2. Initialization: x = 10; (The engine allocates memory).
  3. Usage: console.log(x); (The engine retrieves the value).

2. The Stack vs. The Heap

JavaScript uses two distinct structures to store data. Understanding the difference is key to mastering Value vs. Reference.

A. The Stack (Primitive Types)

  • What it stores: Primitive values (String, Number, Boolean, Null, Undefined, Symbol, BigInt).
  • Behavior: Fast access, fixed size.
  • Mechanism: When you copy a primitive, JS creates a brand new copy of the value.

B. The Heap (Reference Types)

  • What it stores: Objects, Arrays, and Functions.
  • Behavior: Slower access, flexible size.
  • Mechanism: When you “store” an object in a variable, the variable doesn’t actually hold the object. It holds a reference (address) pointing to the location in the Heap where the object lives.

3. Pass by Value vs. Pass by Reference

This is a classic interview topic.

Pass by Value (Primitives)

JavaScript

let name1 = "Alice";
let name2 = name1; // A copy is made

name2 = "Bob"; 

console.log(name1); // "Alice" (Original stays same)
console.log(name2); // "Bob"

Pass by Reference (Objects/Arrays)

JavaScript

let user1 = { name: "Alice" };
let user2 = user1; // Both variables point to the SAME address in the Heap

user2.name = "Bob"; 

console.log(user1.name); // "Bob" (Wait, what?! The original changed!)

Warning: This is why “mutating” objects is dangerous in large apps. Both variables are just different names for the same memory “bucket.”


4. let vs. const vs. var (The Final Verdict)

The var Legacy

  • Scope: Function-scoped.
  • Hoisting: Initialized as undefined.
  • Problem: It ignores block scope (if or for loops), leading to “Variable Leakage.”

The Modern let

  • Scope: Block-scoped (only lives inside { }).
  • Hoisting: Stored in the Temporal Dead Zone.
  • Usage: Use when you know the value will change (e.g., a loop counter).

The Essential const

  • Scope: Block-scoped.
  • Constraint: Must be initialized immediately and cannot be reassigned.
  • Misconception: const does not make objects immutable. It just means the “address” in the stack cannot change.

The const Object Trap:

JavaScript

const colors = ["red", "blue"];
colors.push("green"); // Works perfectly!
// colors = ["yellow"]; // Error! (Trying to change the address)

5. Garbage Collection

How does JS clean up memory? It uses an algorithm called “Mark and Sweep.”

  1. Mark: The engine starts at the “roots” (Global object) and marks everything it can reach.
  2. Sweep: Everything that wasn’t marked (not reachable) is considered “garbage” and deleted to free up space.

Code Challenge: The Reference Mystery

Look at the code below. Without running it, can you guess the output of the final line?

JavaScript

let a = [1, 2, 3];
let b = a;
b.push(4);

let c = [...a]; // This is called "Spreadding"
c.push(5);

console.log(a); 

Explanation:

  • b = a creates a reference. Adding 4 to b also adds it to a.
  • c = [...a] creates a Shallow Copy (a brand new array in the heap). Adding 5 to c does not affect a.
  • Result: a is [1, 2, 3, 4].

In Simple words

What is a Variable?

A variable is a named memory location used to store data that can change during program execution.

Example (conceptual):

  • age = 21
  • salary = 50000

Here, age and salary are variable names, and values are stored in memory.

Why Variables Are Needed

  • Store user input
  • Store intermediate results
  • Control program flow
  • Enable reusability and readability

2. Rules for Naming Variables

Common rules across languages:

  • Must start with a letter or underscore (_)
  • Cannot start with a digit
  • Cannot use keywords (int, class, if)
  • Case-sensitive (Ageage)
  • No spaces or special symbols (@, #, $)

Best Practices

  • Use meaningful names: totalMarks instead of tm
  • Use camelCase or snake_case depending on language
  • Avoid single-letter variables except loop counters

3. Variable Declaration & Initialization

Declaration

Reserves memory for a variable.

Example:

  • int count;
  • float price;

Initialization

Assigning a value to a variable.

Example:

  • int count = 10;
  • float price = 99.99;

Declaration + Initialization Together

  • int x = 5;

4. Types of Variables

1. Local Variables

  • Declared inside functions or blocks
  • Accessible only within that block
  • Stored in stack memory

Example:

function sum() {
   int a = 10;
}

2. Global Variables

  • Declared outside all functions
  • Accessible throughout the program
  • Stored in static memory

3. Static Variables

  • Retain value between function calls
  • Lifetime = entire program
  • Scope limited to block or file

4. Instance Variables (OOP)

  • Belong to objects
  • Each object has its own copy
  • Stored in heap memory

5. Class / Static Variables (OOP)

  • Shared among all objects
  • Single copy in memory

5. Constants

What is a Constant?

A constant is a variable whose value cannot be changed once assigned.

Example:

  • const int MAX = 100;

Why Use Constants?

  • Prevent accidental modification
  • Improve code readability
  • Easier maintenance
  • Improve program safety

6. Types of Constants

1. Literal Constants

Fixed values written directly in code:

  • Integer: 10
  • Float: 3.14
  • Character: 'A'
  • String: "Hello"
  • Boolean: true, false

2. Symbolic Constants

Defined using keywords or macros:

  • const
  • final (Java)
  • #define (C/C++)

3. Enum Constants

Group of named constants.

Example:

enum Days { MON, TUE, WED }

7. Memory Management – Basics

What is Memory Management?

The process of allocating, using, and freeing memory during program execution.

Goals:

  • Efficient use of memory
  • Avoid memory leaks
  • Prevent crashes
  • Improve performance

8. Memory Layout of a Program

Common Memory Segments

Memory AreaPurpose
StackLocal variables, function calls
HeapDynamic memory allocation
Data SegmentGlobal & static variables
Code SegmentProgram instructions

9. Stack Memory

Characteristics

  • Stores local variables
  • Memory allocated automatically
  • Follows LIFO (Last In First Out)
  • Fast access
  • Limited size

Advantages

  • No need for manual deallocation
  • Very fast

Disadvantages

  • Limited memory
  • Cannot store large objects

10. Heap Memory

Characteristics

  • Used for dynamic memory allocation
  • Manual or automatic deallocation (language-dependent)
  • Slower than stack
  • Larger memory space

Use Cases

  • Objects
  • Dynamic arrays
  • Large data structures

11. Static Memory

Characteristics

  • Allocated at compile time
  • Exists throughout program execution
  • Stores global and static variables

12. Dynamic Memory Allocation

Why Dynamic Memory?

  • When memory size is unknown at compile time
  • Efficient memory usage
  • Needed for dynamic data structures

Allocation Methods

  • malloc, calloc, free (C)
  • new, delete (C++)
  • new keyword (Java – handled by JVM)
  • Automatic allocation (Python)

13. Memory Leaks

What is a Memory Leak?

Occurs when memory is allocated but not released after use.

Effects

  • Increased memory usage
  • Performance degradation
  • Program crash

Example (conceptual):

allocate memory
forget to free memory

14. Garbage Collection

What is Garbage Collection?

Automatic memory management system that:

  • Identifies unused objects
  • Frees memory automatically

Languages with GC

  • Java
  • Python
  • JavaScript

Benefits

  • Reduces memory leaks
  • Simplifies development

15. Scope & Lifetime of Variables

Scope

Where a variable is accessible.

Types:

  • Block scope
  • Function scope
  • Global scope

Lifetime

How long a variable exists in memory.

Variable TypeLifetime
LocalDuring function execution
StaticEntire program
GlobalEntire program
ObjectUntil destroyed or garbage collected

16. Pass by Value vs Pass by Reference

Pass by Value

  • Copy of variable is passed
  • Original value unchanged

Pass by Reference

  • Memory address passed
  • Original value can change

17. Common Errors & Best Practices

Common Errors

  • Using uninitialized variables
  • Memory leaks
  • Accessing freed memory
  • Stack overflow

Best Practices

  • Initialize variables
  • Use constants where applicable
  • Minimize global variables
  • Free unused memory
  • Prefer automatic memory management when possible

18. Real-World Examples

  • Variables → User data, scores, prices
  • Constants → PI, TAX_RATE, MAX_USERS
  • Heap → Objects, user profiles
  • Stack → Function calls, loop variables

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥