Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

odd behavior while looping over an array in JavaScript

I'm reading through Eloquent Javascript and facing one of the exercises, I found a rather odd behavior. (at least for me)

the exercise asks to create a function in order to reverse an array. I thought I could loop over the array and each time pop one item from the original array and push it into a temporary array that is going to finally be returned. but as I'm looping over the array either with a for-of loop or typical sequential loop, last item is not transferred.

can someone tell me what happens exactly?

const reverseArray = function(array) {
let rev = [];
for (let x = 0; x <= array.length; x++) {

    rev.push(array.pop());
    console.log(rev, array)
}
return rev;
};


console.log(reverseArray(["A", "B", "C"]));

output:

["C"] ["A", "B"]
["C", "B"] ["A"]
["C", "B"]
like image 962
Behzad Hatami Avatar asked Apr 23 '26 15:04

Behzad Hatami


2 Answers

When the pop() applies on array it decreases the length of the array so when the loop runs it finds one item less than the previous array length. Thus, what you can do is simply assign the length of the array in a variable and use that in the comparison of the for loop:

let rev = [];
const reverseArray = function(array) {
var length = array.length;
for (let x = 0; x < length; x++) {
  rev.push(array.pop());
}
return rev;
};


console.log(reverseArray(["A", "B", "C"]));
like image 96
Ankit Agarwal Avatar answered Apr 25 '26 04:04

Ankit Agarwal


As the pop() method remove the pop'ed item from the array, use a while loop instead of for

let rev = [];
const reverseArray = function(array) {
    while (array.length > 0) {    // or just "(array.length)"
      rev.push(array.pop());
    }
    return rev;
}

console.log(reverseArray(["A", "B", "C"]));

With closure you can save yourself an extra global variable

const reverseArray = function(array) {
  return (function(a_in,a_out) {
    while (a_in.length > 0) {    // or just "(a_in.length)"
      a_out.push(a_in.pop());
    }
    return a_out;
  })(array,[]);
}

console.log(reverseArray(["A", "B", "C"]));

Or if the Array.reverse() method is allowed

const reverseArray = function(array) {
    return array.reverse();
}

console.log(reverseArray(["A", "B", "C"]));
like image 20
Asons Avatar answered Apr 25 '26 05:04

Asons