Different array methods | JavaScript

/ #JavaScript


There are a lot of different things you can do with JavaScript arrays. In this little guide, I'll go through some of them.

Remove the first element (Shifting)

// Define an array
var animals = ['Elephant', 'Tiger', 'Lion'];

// Remove the first
animals.shift();

The array will now only have two elements. If you want to remove the first element, but assign it to a variable instead, you can do this:

// Define an array
var animals = ['Elephant', 'Tiger', 'Lion'];

// Extract the first element
var first = animals.shift();

The array will now only have two elements, and the value of "first" will be "Elephant".

Remove the last element (Popping)

We can do the exact same thing for the last element in an array, we just use "pop" instead of "shift".

// Define an array
var animals = ['Elephant', 'Tiger', 'Lion'];

// Extract the last element
var last = animals.pop();

The array will now only have two elements, and the value of "last" will be "Lion".

Getting the length

If you want to know the length of an array, you can easily get this:

// Define an array
var animals = ['Elephant', 'Tiger', 'Lion'];
var arrayLength = animals.length;

console.log(arrayLength);

This will print "3" in the console.


Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.