Fun with javascript array

1) Slice Vs Splice


Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

array.splice(start,, deleteCount, item1, item2, …itemN)

Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.

An integer indicating the number of old array elements to remove.If omitted, or deleteCount> array.length-start, then all of the elements from start through the end of the array will be deleted.If deleteCount=<0 negative, no elements are removed.

Values to replace or add.

1) Remove last two elements.
var months = [‘Jan’, ‘March’, ‘April’, ‘June’];
console.log(months); // [“Jan”, “March”]

2) Remove all elements from Array
var months = [‘Jan’, ‘March’, ‘April’, ‘June’];
console.log(months); // []

var months = [‘Jan’, ‘March’, ‘April’, ‘June’];
console.log(months); // []

3) Insert an element at a position
var months = [‘Jan’, ‘March’, ‘April’, ‘June’];
console.log(months); // [“Jan”, “Ap”, “March”, “April”, “June”]

4) Remove elements and add a new element
var months = [‘Jan’, ‘March’, ‘April’, ‘June’];
console.log(months); // [“Jan”, “Ap”, “June”]


Returns a shallow copy of a portion of an array into a new array object selected from begin to end(end not included). The original array will not be modified.
var animals =[‘ant’,‘bison’,‘camel’,‘duck’,‘elephant’];
// expected output: Array [“camel”, “duck”, “elephant”]
console.log(animals.slice(2, 4));
// expected output: Array [“camel”, “duck”]
console.log(animals.slice(1, 5));
// expected output: Array [“bison”, “camel”, “duck”, “elephant”]

Delete operations on an Array

1) Using delete operator:
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

var Employee =[1,2,3]
delete Employee[2];
console.log(Employee); // [1, 2, undefined]

2) Using Splice

Shift operations on an Array

  1. unshift()
    Adds one or more elements to the beginning of an array and returns the new length of the array.
    var array1 = [1, 2, 3];
    console.log(array1.unshift(4, 5,8));
    // expected output: 6.The length of the array is 6 now.
    // expected output: Array [4, 5, 8, 1, 2, 3]

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store