Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do-While loop output is undefined

the console shows undefined for the following loop. the issue is in array[i]
as it says i is undefined but it is the index for the loop elements. I don’t want to change the x to I as I want to run the code only once and test that it will stop as x is not < 5.

let x = 5;
let i;
let array = ["x", "y", "z"];
do {
  console.log(array[i]); //statement
  i++; //increment
} while (x < 5); //condition

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so the problem with your code is that you initialised i without difining it let i; and then you are incrementing it i++,
set let i = 0;

let x = 5;
let i = 0;
let array = ["x", "y", "z"];
do {
  console.log(array[i]); //statement
  i++; //increment
} while (x < 5); //condition

now if x is not less than 5 then the loop will run once
but there will be a problem that if x is less than 5 then loop will run infinitely so instead of just x < 5 dot x < 5 && i < array.length

let x = 4;
let i = 0;
let array = ["x", "y", "z"];
do {
  console.log(array[i]); //statement
  i++; //increment
} while (x < 5 && i < array.length); //condition

now it will work just fine !

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading