Array Reverse is not working for me ...

TheWebs picture TheWebs · Mar 3, 2016 · Viewed 19.4k times · Source

Consider the following code (React JS code):

  poll() {
    var self   = this;
    var url    = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40';

    $.get(url, function(result) {
      console.log(result.data, result.data.reverse());
      self.setState({
        error:          null,
        historicalData: result.data.reverse(),
        isLoading: false
      });
    }).fail(function(response) {
      self.setState({
        error: 'Could not fetch average price data. Looks like something went wrong.',
      });
    });
  }

Notice the console.log. Lets see an image:

enter image description here

Last I checked, reverse should have reversed the order of the array. Yet it doesn't.

Am I Using this wrong (official MDN Docs)? Why isn't reverse working?

Answer

Matt Harrison picture Matt Harrison · Mar 3, 2016

It has reversed it, the reverse() is executed before the console.log(). It mutates the actual array first in place returning a reference so then when it is logged, a is also reversed.

var a = [1,2,3,4];
console.log(a, a.reverse());
// [4, 3, 2, 1] [4, 3, 2, 1]

Everything inside the console.log parens is evaluated first. Try 2 reverses, can you guess what happens, it goes back to original order, like in your example.

var a = [1,2,3,4]
console.log(a, a.reverse(), a.reverse());
// [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]