vince collab
vince collab

Reputation: 13

Why putting 0 as a first element of array prevent "for" loop execution. [JavaScript]

Consider the following JavaScript code:

var words = delIdx = [0, 1, 2, 3];
for(let i=0; delIdx[i]; i++) {
  console.log('DELIDX: ', delIdx[i]);
}

for(let i=0; words[i]; i++) {
  console.log('Word: ', words[i]);
}

words and delIdx are arrays, as you can see the array's first element is set to 0 (zero) and the below two FOR loops are using these arrays to control the execution of the loops. But when 0 is the first element of the loop it doesn't work. It doesn't enter any of the loop at all.

If I change the array's value to var words = delIdx = [2, 3, 4, 5] then the loops works perfectly.

Has anybody experienced this issue? Why is it so? Is it a bug in the JavaScript?

I experienced this in Node.js v5.3.0 and FireFox 44.0.2 console.

Any thoughts?

Thanks.

Upvotes: 1

Views: 217

Answers (2)

Arslan Bilal
Arslan Bilal

Reputation: 625

Because when it evaluates 0 it will return false that's why loop is not working but when you remove 0 form array it will return true and the loop works fine you can also traverse your array by using this code,

var words = delIdx = [0, 1, 2, 3];
for(var i=0; i<delIdx.length; i++) {
  console.log('DELIDX: ', delIdx[i]);
}

for(var i=0; i<words.length; i++) {
  console.log('Word: ', words[i]);
}

Upvotes: 0

Damien Fayol
Damien Fayol

Reputation: 958

When you are using a for loop in javascript, the middle part is supposed to be the predicate:

  • if it evaluates to true, looping continues
  • if it evaluates to false, looping stops

Here you are passing it 0, which evaluates to false, so no looping happens.

Upvotes: 3

Related Questions