how to print an array in reverse javascript code example

Example 1: how to reverse an array in javascript

array = [1 2, 3]
reversed = array.reverse()

Example 2: array reverse algorithm in js

let array1 = ["yes", "no", "maybe", "always", "sometimes", "never", "if"];
let array2 = [5,8,2,9,5,6,3,1];

function reverseArray(arr) {
  var newArray = [];
  for (var i = arr.length - 1; i >= 0; i--) {
    newArray.push(arr[i]);
  }
  return newArray;
}

reverseArray(array1); // ["if", "never", "sometimes", "always", "maybe", "no", "yes"]
reverseArray(array2); // [1, 3, 6, 5, 9, 2, 8, 5]

Example 3: reverse array javascript

// reverse array with recursion function
function reverseArray (arr){
if (arr.length === 0){
return []
}
  return [arr.pop()].concat(reverseArray(arr))
}
console.log(reverseArray([1, 2, 3, 4, 5]))

Example 4: reverse an array javascript

const reversed = array1.reverseconst reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]