DEV Community

Cover image for 🔥Exploring Basic Array Methods in JavaScript
Noor Fatima
Noor Fatima

Posted on

🔥Exploring Basic Array Methods in JavaScript

Arrays are fundamental in JavaScript, allowing us to store multiple values in a single variable. To manage these arrays effectively, JavaScript provides several methods. In this article, we’ll explore some basic array methods: push(), pop(), toString(), concat(), unshift(), and shift().

Push( ) : Add to End

The push() method adds one or more elements to the end of an array and returns the new length of the array.

let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]

Enter fullscreen mode Exit fullscreen mode

Pop( ) : Delete from End & Return

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: "orange"
console.log(fruits); // Output: ["apple", "banana"]

Enter fullscreen mode Exit fullscreen mode

toString( ) : Convert Array to String

The toString() method converts an array into a string, with each element separated by a comma.

let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.toString();
console.log(fruitString); // Output: "apple,banana,orange"

Enter fullscreen mode Exit fullscreen mode

Concat( ) : Join Multiple Arrays

The concat() method is used to merge two or more arrays. This method does not change the existing arrays but returns a new array.

let fruits = ["apple", "banana"];
let moreFruits = ["orange", "mango"];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ["apple", "banana", "orange", "mango"]

Enter fullscreen mode Exit fullscreen mode

Unshift( ) : Add to Start

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // Output: ["apple", "banana", "orange"]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)