Array Methods
Introduction to Array Methods in JavaScript
Arrays are very useful when it comes to storing and managing multiple values in a single variable. But, their true power lies in the various methods they provide to manipulate and manage data. In this tutorial, we will learn about several important array methods in JavaScript that will help you to handle arrays effectively.
Array.length
The length
property returns the number of elements in an array.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.length); // Output: 3
Array.push()
The push()
method adds new items to the end of an array and returns the new length.
let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
Array.pop()
The pop()
method removes the last element from an array and returns that element.
let fruits = ["Apple", "Banana", "Cherry"];
let last = fruits.pop();
console.log(last); // Output: "Cherry"
Array.shift()
The shift()
method removes the first element from an array and returns that element.
let fruits = ["Apple", "Banana", "Cherry"];
let first = fruits.shift();
console.log(first); // Output: "Apple"
Array.unshift()
The unshift()
method adds new items to the beginning of an array and returns the new length.
let fruits = ["Apple", "Banana"];
fruits.unshift("Cherry");
console.log(fruits); // Output: ["Cherry", "Apple", "Banana"]
Array.splice()
The splice()
method adds/removes items to/from an array and returns the removed item(s).
let fruits = ["Apple", "Banana", "Cherry"];
fruits.splice(1, 0, "Orange");
console.log(fruits); // Output: ["Apple", "Orange", "Banana", "Cherry"]
Array.slice()
The slice()
method returns a shallow copy of a portion of an array into a new array object.
let fruits = ["Apple", "Banana", "Cherry"];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ["Banana", "Cherry"]
Array.join()
The join()
method creates and returns a new string by concatenating all of the elements in an array.
let fruits = ["Apple", "Banana", "Cherry"];
let str = fruits.join(", ");
console.log(str); // Output: "Apple, Banana, Cherry"
Array.sort()
The sort()
method sorts the items of an array in place and returns the array. By default, the sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.
let fruits = ["Cherry", "Banana", "Apple"];
fruits.sort();
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
Array.reverse()
The reverse()
method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
let fruits = ["Apple", "Banana", "Cherry"];
fruits.reverse();
console.log(fruits); // Output: ["Cherry", "Banana", "Apple"]
This tutorial covered the basic array methods in JavaScript. Mastering these methods will help you manipulate and manage data effectively using arrays. Keep practicing them to get a good grasp. Happy coding!