JavaScript Array Reference
JavaScript Array Reference
In JavaScript, arrays are reference types, which means that when you assign an array to another variable, both variables point to the same array in memory. Changing one will affect the other.
🔹 Example 1: Array Reference
✅ Both arrays changed because they refer to the same object.
🔹 Example 2: Copying Arrays Properly
To avoid modifying the original array, create a shallow copy:
Using slice()
Using Spread Operator ...
🔹 Why This Happens
-
Arrays (and objects) are stored by reference.
-
Primitive types (numbers, strings, booleans) are stored by value.
🔹 Important Notes
-
Modifying a reference array affects all variables pointing to it.
-
Use slice, spread operator, or
Array.from()to create a copy if needed.
Example: Array.from()
Summary Table
| Concept | Behavior |
|---|---|
| Arrays | Reference type |
| Objects | Reference type |
| Numbers/Strings/Booleans | Value type |
| Copy array safely | slice(), [...array], Array.from() |
