skip to Main Content

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


  1. Your code will result in an infinite loop !!

    Firstly, you have declared i but have not initialized it with a value. This means i will be undefined, and when you use it as an index to access array[i], it will always be undefined, resulting in an infinite loop.

    Secondly, in your while loop condition, you are checking array[i] != 'undefined'. This comparison should be array[i] !== undefined (without the quotes around undefined). The undefined keyword should not be treated as a string in this case.

    let array = [1, 2, 3, 4, 5];
    let i = 0;
    let count = 0;
    
    while (array[i] !== undefined) {
        console.log(array[i]);
        i++;
        count++;
    }
    
    console.log("Length of array is " + count);

    I hope I helped you learn something new today 😉

    Login or Signup to reply.
  2. A modern forEach() loop seems simpler here. You don’t need to bother with indexes.

    let array = [1, 2, 3, 4, 5];
    let count = 0;
    
    array.forEach(element => {
      count++;
    });
    
    console.log("length of array is " + count);
    console.log('array.length is', array.length);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search