Array method in Javascript

Array method in Javascript

Day 6 of 30 days of Javascript Interview

  1. push(): Adds one or more elements to the end of an array and returns the new length of the array.
let  arr = [1, 2, 3];
arr.push(4);
// arr is now [1, 2, 3, 4]
  1. pop(): Removes the last element from an array and returns that element.
let  arr = [1, 2, 3];
let removedElement = arr.pop();
// arr is now [1, 2], removedElement is 3
  1. shift(): Removes the first element from an array and returns that element.
let  arr = [1, 2, 3];
let shiftedElement = arr.shift();
// arr is now [2, 3], shiftedElement is 1
  1. unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
let  arr = [2, 3];
arr.unshift(1);
// arr is now [1, 2, 3]
  1. slice(): Returns a shallow copy of a portion of an array into a new array. You can specify start and end indices.
let  arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(1, 3);
// newArr is [2, 3], arr remains [1, 2, 3, 4, 5]
  1. splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
let  arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 'a', 'b');
// arr is now [1, 2, 'a', 'b', 4, 5]
  1. forEach(): Executes a provided function once for each array element.
let  arr = [1, 2, 3];
arr.forEach(function(element) {
  console.log(element);
});
// Output: 1
//         2
//         3
  1. map(): Creates a new array populated with the results of calling a provided function on every element in the calling array.
let  arr = [1, 2, 3];
let newArr = arr.map(function(element) {
  return element * 2;
});
// newArr is [2, 4, 6]