Skip to content

Variables and Data Types

Variables are used to store data values in memory so they can be reused and manipulated later in a program.

JavaScript provides three ways to declare variables:

  • var (old, function-scoped)
  • let (modern, block-scoped)
  • const (block-scoped, constant reference)

var

Function-scoped, allows redeclaration, hoisted with undefined.

let

Block-scoped, cannot be redeclared, safer alternative to var.

const

Block-scoped, cannot be reassigned after initialization.


graph TD A[Variable Declaration] --> B[Memory Allocation] B --> C[Identifier: x] C --> D[Value: 10]

When you write:

let x = 10;
  • Memory is allocated
  • Identifier x is created
  • Value 10 is stored

var x = 10;
var x = 20; // allowed
  • Function scoped
  • Can be redeclared
  • Hoisted with undefined

Scope defines where a variable is accessible.

graph TD A[Global Scope] --> B[Function Scope] B --> C[Block Scope]
  • Global Scope → accessible everywhere
  • Function Scope → inside functions (var)
  • Block Scope → inside {} (let, const)

{
let a = 10;
var b = 20;
}
console.log(b); // ✅ works
console.log(a); // ❌ error


Hoisting is JavaScript’s behavior of moving declarations to the top of their scope.

graph TD A[Code Written] --> B[Hoisted Phase] B --> C[Execution Phase]

console.log(x);
var x = 10;

Internally becomes:

var x;
console.log(x); // undefined
x = 10;

console.log(x); // ❌ ReferenceError
let x = 10;

This happens due to Temporal Dead Zone (TDZ).



JavaScript has two main categories:

Primitive Types

Immutable values stored directly.

Reference Types

Stored as references (memory address).


  1. Number Represents integers and floating numbers. Example: 10, 3.14

  2. String Sequence of characters. Example: "Hello"

  3. Boolean true or false

  4. Undefined Variable declared but not assigned

  5. Null Intentional empty value

  6. Symbol Unique identifier

  7. BigInt Large integers beyond Number limit


  • Objects
  • Arrays
  • Functions

graph LR A[Primitive] --> B[Value Stored Directly] C[Reference] --> D[Stored in Heap] D --> E[Reference Address]

let a = 10;
let b = a;
b = 20;
console.log(a); // 10
let obj1 = { name: "Sahil" };
let obj2 = obj1;
obj2.name = "Kumar";
console.log(obj1.name); // Kumar


Used to detect type of variable.

typeof 10; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (bug)

Use let instead of var

Avoid bugs caused by function scope.

Use const by default

Only use let when reassignment is needed.

Avoid global variables

Keeps code clean and predictable.

Understand scope deeply

Prevents logical errors.