JavaScript provides a rich set of built-in methods to work with arrays. These methods allow you to easily add, remove, modify, and combine array elements.
toString() and join()toString(): Converts an array to a comma-separated string of array values.join(separator): Joins all array elements into a string. You can specify a separator; if none is provided, it defaults to a comma.const fruits = ["Banana", "Orange", "Apple", "Mango"];console.log(fruits.toString()); // "Banana,Orange,Apple,Mango" console.log(fruits.join(" * ")); // "Banana * Orange * Apple * Mango"
push() and pop() (End of Array)pop(): Removes the last element from an array and returns that element.push(): Adds a new element to the end of an array and returns the new length.const fruits = ["Banana", "Orange", "Apple"];fruits.pop(); // Removes "Apple" console.log(fruits); // ["Banana", "Orange"]
fruits.push("Kiwi"); // Adds "Kiwi" to the end console.log(fruits); // ["Banana", "Orange", "Kiwi"]
shift() and unshift() (Start of Array)shift(): Removes the first element from an array and returns that element.unshift(): Adds a new element to the beginning of an array and returns the new length.const fruits = ["Banana", "Orange", "Apple"];fruits.shift(); // Removes "Banana" console.log(fruits); // ["Orange", "Apple"]
fruits.unshift("Lemon"); // Adds "Lemon" to the beginning console.log(fruits); // ["Lemon", "Orange", "Apple"]
splice()The splice() method can be used to add or remove elements from anywhere in an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];// At index 2, remove 1 element and add "Lemon" and "Kiwi" fruits.splice(2, 1, "Lemon", "Kiwi");
console.log(fruits); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
slice()The slice() method slices out a piece of an array into a new array. It does not modify the original array.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];// Slice from index 1 up to (but not including) index 3 const citrus = fruits.slice(1, 3);
console.log(citrus); // ["Orange", "Lemon"] console.log(fruits); // Original array is unchanged
concat()The concat() method creates a new array by merging (concatenating) existing arrays.
const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"];const myChildren = myGirls.concat(myBoys);
console.log(myChildren); // ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]
Which method adds a new element to the beginning of an array?