Copy objects, arrays and arrays of objects in Javascript

Copy objects, arrays and arrays of objects in Javascript

Primitive values like string, number, boolean are immutable. They cannot be modified and only copied. The Javascript engine make a copy of the variable in assignment declaration. When assigning a new value to the variable, the previous variable is cleared out of the memory of the engine and a new variable is created.

Reference values like arrays, objects and even functions, are mutable. They CAN be changed since the Javascript engine uses a pointer to reference the variable in memory. Consequently, objects and arrays can be edited without copying the value first.

How can we make an exact copy of an array, an objects or a function?

Copying an array:

const hobbies = ['Football', 'Cinema', 'Netflix'];
const todos = hobbies.slice(); // use slice method without any parameters

OR

const todos = [...hobbies]

Copying an object:

const user = { name: 'Shane', age: 35};
const employee = Object.assign({}, user); // 2 param: to object, from object. The to object it an empty object in this example

OR

const employee = {...user};

Copying an array of objects:

const users = [{name: 'Shane'}, {name: 'Shekina'}];
const students = users.map(usr => {   // the map method creates a new array from the users array with item, usr
    return {...usr}; // we destructure the usr into the new array
});

OR

const students = [...users]; // Inconvenient solution: This one makes a copy of the array,, however the objects in the array are still pointing to the same old pointers from users array