Access an array in reverse.
Consider the array in the code block below -
const nums = [1, 2, 3];
Accessing the array is easy enough.
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
/* 1 2 3 */
But, what if you want to access the array from the last element?
Use pop
We have seen one of the ways to do that using pop.
console.log(nums.pop());
console.log(nums.pop());
console.log(nums.pop());
/* 3 2 1 */
But, this changes the array.
console.log(nums);
// []
Use slice
If you want to just access the array from the last element, but not change the array -
console.log(nums.slice(-1, 3));
console.log(nums.slice(-2, 2));
console.log(nums.slice(-3, 1));
// [3] [2] [1]
Or..
console.log(nums.slice(-1, nums.length));
console.log(nums.slice(-2, nums.length - 1));
console.log(nums.slice(-3, nums.length - 2));
// [3] [2] [1]
To reverse parts of the array or the whole of it -
console.log(nums.slice(-1));
console.log(nums.slice(-2));
console.log(nums.slice(-3));
// [ 3 ] [ 2, 3 ] [ 1, 2, 3 ]
Use reverse
Instead of accessing the array from the reverse, make reverse the new forward.
const nums = [1, 2, 3];
const numsRv = nums.reverse();
console.log(numsRv[0]);
console.log(numsRv[1]);
console.log(numsRv[2]);
// 3 2 1
To retain the original array..
const nums = [1, 2, 3];
const numsRv = nums.slice().reverse();
console.log(numsRv[0]);
console.log(numsRv[1]);
console.log(numsRv[2]);
// 3 2 1
console.log(nums);
// [1, 2, 3]
Which options should I choose?
What you choose really depends on what you want to do with the result and with the original array. I would personally use a pop on an array clone to make the code look squeaky clean and run a bit faster.
const nums = [1, 2, 3];
const numsCp = nums.slice();
console.log(numsCp.pop());
console.log(numsCp.pop());
console.log(numsCp.pop());
// 3 2 1
console.log(nums);
// [ 1, 2, 3 ]