JavaScript Array Reference

JavaScript Tutorial

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

ConceptBehavior
ArraysReference type
ObjectsReference type
Numbers/Strings/BooleansValue type
Copy array safelyslice(), [...array], Array.from()

You may also like...