About Lesson
JavaScript Value vs. Reference Types
In JavaScript, data types are broadly classified into two categories:
-
Primitive (Value) Types:
- Store the actual value directly.
- Examples:
Number
(e.g., 10, 3.14)String
(e.g., “hello”, ‘world’)Boolean
(e.g., true, false)null
(represents the intentional absence of a value)undefined
(represents a variable that has been declared but has no value assigned)Symbol
(unique and immutable values)
-
Reference Types:
- Store a reference (memory address) to the actual value.
- Examples:
Object
(e.g.,{ name: "John", age: 30 }
)Array
(e.g., [1, 2, 3])Function
Key Differences:
-
Assignment:
- Value Types: When assigned to a new variable, a new copy of the value is created. Changes to the new variable do not affect the original.
- Reference Types: When assigned to a new variable, both variables point to the same memory location. Changes made to one variable will also affect the other.
-
Example:
JavaScript// Value Type (Number) let num1 = 10; let num2 = num1; num2 = 20; console.log(num1); // Output: 10 // Reference Type (Array) let arr1 = [1, 2, 3]; let arr2 = arr1; arr2.push(4); console.log(arr1); // Output: [1, 2, 3, 4]
Understanding this distinction is crucial for writing correct and predictable JavaScript code, especially when dealing with object manipulation and function arguments.