JAVASCRIPT ARRAY METHODS

Push

The push() method is used to add one or more elements to the end of an array. It modifies the original array by adding the provided elements and returns the new length of the array.

const arr = ['Apple', 'Mango'];
arr.push('Banana');
console.log(arr);

// ['Apple', 'Mango', 'Banana']

Shift

The shift() method removes the first element from an array and shifts all other elements down by one position. It returns the removed element and modifies the original array.

const arr = ['Apple', 'Mango', 'Banana'];
arr.shift();
console.log(arr);

// ['Mango', 'Banana']

Pop

The pop() method removes the last element from an array and returns that element. It modifies the original array by reducing its length by one.

const arr = ['Apple', 'Mango', 'Banana'];
arr.pop();
console.log(arr);

// ['Apple', 'Mango']

Slice

The slice() method creates a new array that contains a shallow copy of a portion of an existing array. It takes two optional parameters: `start` (inclusive) and `end` (exclusive), specifying the start and end positions of the slice. If not provided, it copies the entire array.

const arr = ['Apple', 'Mango', 'Banana'];
const res = arr.slice(1, 3);
console.log(res);

// ['Mango', 'Banana']

ToString

The toString() method converts an array to a string and returns the resulting string. It joins the array elements into a comma-separated string.

const arr = ['Apple', 'Mango', 'Banana'];
const res = arr.toString();
console.log(res);

// Apple,Mango,Banana

Map

The map() method creates a new array by applying a provided function to each element of the calling array. It executes the provided function once for each array element and returns a new array with the results.

const arr = [3, 5, 7, 9];
const res = arr.map(val => {
  return val*3;
})
console.log(res)

// [9, 15, 21, 27]

Filter

The filter() method creates a new array with all elements that pass a provided test. It executes the provided function once for each element in the array and includes the element in the new array if the function returns `true`.

const res = arr.filter(val => {
  return val > 5;
})
console.log(res)

// [7, 9]

Includes

The includes() method takes one required parameter: the element to search for within the array. It performs a strict equality comparison (using the === operator) to determine if the element is present.

const arr = ['Apple', 'Tomato', 'Banana'];
const res = arr.includes('Tomato', 0);
console.log(res);

// true

Leave a Comment

Your email address will not be published. Required fields are marked *