spread operator in Javascript

spread operator in Javascript

·

2 min read

you have been using spread (...)operator in javascript/typescript in your projects for a long time. but did you ever know why is it used ?

let me explain it.

lets understand what are arrays:

arrays are fixed sized, continuous, physical memory chunks. fixed sized means once defined you can’t grow it because of how memory allocation works and nature of it as a data structure.

whenever an array is created a fixed memory is allocated to it. if you want to add more elements to the array it isn’t guaranteed that there will be free space after the array’s allocated block in the physical memory. there are some more reasons also like efficiency concerns, memory management and safety.

here’s code example of how it works :

let originalArray = [1, 2, 3];

// Create a new array, incorporating elements from the original array
let newArray = [...originalArray, 4, 5];

console.log(newArray); // Output: [1, 2, 3, 4, 5]

originalArray has fixed allocated memory as when it was defined. now to add new elements to it we define newArray and using spread operator we copy the elements of originalArray and add more elements as we need and store it in newArray which is a new fixed, continuous allocation of memory different from the originalArray .

hi, i am shivam. you can contact me here shivamsharma.net .