Add element to an array in JavaScript
Add element at the beginning (left) of the array using the spread operator
const arr = [1, 2, 3];
[0, ...arr]; // [0, 1, 2, 3]
Add element at the beginning (left) of the array using unshift
const arr = [1, 2, 3];
arr.unshift(0); // returns new length: 4
arr; // [0, 1, 2, 3]
Add element at end (right) of the array using the spread operator
const arr = [1, 2, 3];
[...arr, 4]; // [1, 2, 3, 4]
Add element at the end (right) of the array using push
const arr = [1, 2, 3];
arr.push(4); // returns new length: 4
arr; // [1, 2, 3, 4]
The spread operator does not change the original array, while the push
changes.
Mnemonic. SHOP removes: shift (left) + pop (right)
And unshift
does the opposite of shift
.
If you know a better mnemonic let me know! You could google it, but that interrupts your work.
Questions
What's the output?
const arr = [1, 2];
const res = [44, ...arr];
console.log(res);
What's the output of console.log?
const arr = [1, 2];
arr.unshift(44);
console.log(arr); // ??
What's the output?
const arr = [1, 2];
const res = [...arr, 44];
console.log(res)
What's the output of console.log?
const arr = [1, 2];
arr.push(44);
console.log(arr); // ??
What's the output of console.log?
const arr = [1, 2];
const x = arr.push(44);
console.log(x); // ??
What's the output of console.log?
const arr = [1, 2];
const x = arr.unshift(44);
console.log(x); // ??
What's the output?
const arr = [1, 2];
const res = [44, ...arr];
console.log(arr);