JavaScript Glossary - Lesson #14

JavaScript Array .reverse() Method

This method changes the position of elements within the array. The first element goes to the last position and the last element goes to the first position. The method returns the reversed array.

js
[1, 2, 3, 4, 5].reverse()
// [5, 4, 3, 2, 1]
js
//  List of items
const list = ['fish', 'cow', 'ham', 'ram', 'table']

//  Reverse list
list.reverse()

// Output result
console.log(list) // ["table","ram","ham","cow","fish"]
js
array.reverse()

The method will return the reversed array.

js
const numbers = [1, 2, 4, 5, 6, 7];
const reversed = numbers.reverse();
// reversed: Array [7, 6, 5, 4, 2, 1]

Take care when using .reverse() as it mutates the calling array

When an array of elements are returned in a reversed order. The reverse method will restore order.

Flip the months:

js
// Array of months
const months = ['Dec', 'Nov', 'Oct', 'Sept', 'Aug', 'July', 'June', 'May', 'April', 'Mar', 'Feb', 'Jan'];

// Reverse order of array
const monthsInOrder = months.reverse();

// Output result
console.log(monthsInOrder);
// ["Jan","Feb","Mar","April","May","June","July","Aug","Sept","Oct","Nov","Dec"]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)