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

let fruits = ["Apple", "Banana"];
let newFruits = fruits; // newFruits references the same array

newFruits.push("Mango");

console.log(fruits); // ["Apple", "Banana", "Mango"]
console.log(newFruits); // ["Apple", "Banana", "Mango"]

✅ 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()

let fruits = ["Apple", "Banana"];
let copyFruits = fruits.slice();
copyFruits.push("Mango");

console.log(fruits); // ["Apple", "Banana"]
console.log(copyFruits); // ["Apple", "Banana", "Mango"]

Using Spread Operator ...

let copyFruits2 = [...fruits];
copyFruits2.push("Orange");

console.log(fruits); // ["Apple", "Banana"]
console.log(copyFruits2); // ["Apple", "Banana", "Orange"]


🔹 Why This Happens

  • Arrays (and objects) are stored by reference.

  • Primitive types (numbers, strings, booleans) are stored by value.

let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (original unchanged)

🔹 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()

let original = [1, 2, 3];
let copy = Array.from(original);
copy.push(4);

console.log(original); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]


Summary Table

Concept Behavior
Arrays Reference type
Objects Reference type
Numbers/Strings/Booleans Value type
Copy array safely slice(), [...array], Array.from()

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *