Why reducing the length of an array makes last element undefined but the length doesn't change?

Viewed 167

Hello I'm new to javascript.

I was trying to reduce the length of an array by 1.

I did this, the last element is undefined now, but the length is still 5.

var arr = [1, 2, 3, 4, 5];
arr.length = arr.length--;

console.log(arr);
console.log(arr.length);

I'm confused. Instead of [1, 2, 3, 4] or [1, 2, 3, 4, 5]. Why it gives me [1, 2, 3, 4, undefined]?

Can someone explain? Thanks

5 Answers

arr.length-- will reduce the length by 1 already but will return the previous length, meaning you're reducing the array's length by 1 and then immediately assigning the previous length to arr.length, meaning you're changing it back to a five element array (but you already removed the fifth element ,so that's now undefined.

If you want to just reduce the array's length, you can user arr.length--; alone.

var arr = [1, 2, 3, 4, 5];
arr.length--;

console.log(arr);
console.log(arr.length);

You need to use array.prototype.pop you instead to reduce the size of your array:

var arr = [1, 2, 3, 4, 5];
 arr.pop();

console.log(arr);
console.log(arr.length);

Take into consideration that arr.length-- with a length of 0 causes an error.

A timeline of what's happening in array.length = array.length--:

  • The -- operator changes array.length from 5 to 4.
  • array.length-- evaluates to the previous value of array.length, which is 5
  • This value is assigned to array.length, changing it from 4 to 5.

So you are shrinking the array and then growing it.

My advice: avoid mutating your arrays and instead use slice:

var arr = [1, 2, 3, 4, 5];

var newArr = arr.slice(0, -1);

console.log(newArr);
console.log(newArr.length);

If you insist on mutating your arrays, then I suggest you use a less mystifying operator: -=:

var arr = [1, 2, 3, 4, 5];
arr.length -= 1;

console.log(arr);
console.log(arr.length);

var arr = [1, 2, 3, 4, 5];
    
arr.splice(arr.length-1);

console.log(arr);        //[1,2,3,4]   --Expected Log 
console.log(arr.length); //4           --Expected Log 

Or you can try this:

var arr = [1, 2, 3, 4, 5];

arr.pop();

console.log(arr);        //[1,2,3,4]   --Expected Log 
console.log(arr.length); //4           --Expected Log 

if you want reduce , you can use 'splice'

Related