0

I'm new to JavaScript. I want to remove last element from an array, without using pop method. I've tried using length property, but I'm getting undefined in my console. Please help!

function lastElement(array) {

   return array[array.length-1];

}

lastElement([3,4,5,6]);
msanford
  • 11,803
  • 11
  • 66
  • 93
Jojo
  • 71
  • 1
  • 2
  • 5

2 Answers2

8

Use slice()

function lastElement(array) {
   return array.slice(0,array.length-1);
}

lastElement(array);
Void Spirit
  • 879
  • 6
  • 18
1

You need to take the element first and then decrement the array length.

BTW, the handed over parameters are not an array. You need an array for this task, because if you take only arguments, the length change makes no sense.

function lastElement(array) {
    var temp = array[array.length - 1];
    array.length = Math.max(0, array.length - 1); // prevent assigning negative values
    return temp;
}

var array = [3, 4, 5, 6];

console.log(lastElement(array));
console.log(lastElement(array));
console.log(lastElement(array));
console.log(lastElement(array));
console.log(lastElement(array));
console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392