When we remove an element from array, a null or undefined remains in its place. One of the option is to use removeNullUndefinedEmptyFromArray() function to clean the array. But if you want to remove first element from array then javascript provides two functions for it – Splice() and Shift().

Method 1 – Using Splice()

Splice() can be used to remove elements from any position of the array. It rearranges the elements automatically and do not leave any null or undefined values. Here is the code to remove first element using splice –

var arr = ['a', 'b', 'c', 'd'];
arr.splice(0, 1);
// Output: arr = ['b', 'c', 'd']

Β Β Β Β Tweet this to help others

The parameters of splice are (0, 1) –

  1. First parameter is 0 which indicates the position or index of element to remove. We want to remove first element so index is 0.
  2. Second parameter is 1 which indicates the number of elements to remove. Here we just want to remove 1st element only.

Learn more about Splice() here –

Method 2 – Using Shift()

Shift() is specifically created for removing the first element. Just like pop() method removes the last element, it removes the first. Check out the code –

var arr = ['a', 'b', 'c', 'd'];
arr.shift();
// Output: arr = ['b', 'c', 'd']

Live Demo

You may also like this –

Tagged in:

,

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles