I’m trying to find length of array without built-in length property. Is this a right way? It is going in infinite loop.
let array = [1, 2, 3, 4, 5];
let i;
let count = 0;
while (array[i] != 'undefined') {
console.log(array[i]);
i++
count++;
}
console.log("length of array is" + count);
2
Answers
Your code will result in an infinite loop !!
Firstly, you have declared
i
but have not initialized it with a value. This meansi
will beundefined
, and when you use it as an index to accessarray[i]
, it will always beundefined
, resulting in an infinite loop.Secondly, in your while loop condition, you are checking
array[i] != 'undefined'
. This comparison should bearray[i] !== undefined
(without the quotes around undefined). The undefined keyword should not be treated as a string in this case.I hope I helped you learn something new today 😉
A modern
forEach()
loop seems simpler here. You don’t need to bother with indexes.