Why the first block working fine and second block throwing error?

//1st block
var arr = ['brinth', 'sam', 'ram', 'dom'];
var length = arr.length;
while (length--) {
    console.log('ab');
}
//second block
var arr = ['brinth', 'sam', 'ram', 'dom'];
var length = arr.length;
while (arr.length--) {
    console.log('ab');
}

You’ve already set length to be arr.length. In the next line you say while (arr.length–), which would work out to be (arr.arr.length–), which doesn’t exist. So the first block works and the second does not.

2 Likes

No, thats not the error that’s generated.

The error that the second block generates is because it tries to set an array’s length to -1 when it gets to the last execution evaluation, and that is an invalid array length.

3 Likes

As an aside, don’t play with an array’s length this way. It’s difficult to read and understand what you’re trying to do, as most people would assume an array’s length to be a read-only property. (Which was my assumption too).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.