DEV Community 👩‍💻👨‍💻

Discussion on: problem with this Javascript code, im noob btw

Collapse
 
mranyx profile image
MrAnyx • Edited on

Probably something like this would do the job.

let numbers = [1, 2, 3, 4, 5, 6];
var i = 0;
while(i<numbers.length){
   if(numbers[i] % 2 != 0){
      continue;
   }
   console.log(numbers[i]):
   i++
}

You could also do the same thing using a for-loop

let numbers = [1, 2, 3, 4, 5, 6];
for(let i = 0; i<numbers.length; i++){
   if(numbers[i] % 2 != 0){
      continue;
   }
   console.log(numbers[i]):
}

Something i don't understand is that, in your post title, you've mentioned that you're using javascript, but, to display something in the console using javascript, you should use console.log not print because the print command displays the pop window to print something with your printer.

Collapse
 
commodore1 profile image
Commodore-1 Author

ah thank you man! appreciate it so much!

Collapse
 
commodore1 profile image
Commodore-1 Author

yes i use 2 online compiler to learn basics right now jsbin and other one, one of them needs print to print out the result, i went to check on both sites before posting here thats why this copy paste i did here was with print command, thanks for solving this code for me, hit a like so bad on that, little bit stupid i think of me

Collapse
 
genspirit profile image
Genspirit

I don't use continue often but doesn't it break the loop iteration? Meaning that would lead to an infinite loop in the while example because i would not get incremented.

Collapse
 
mranyx profile image
MrAnyx

Yeah, i forgot that point, if you're using a while loop, you should increment i before the if statement. otherwise, it will create an infinite loop. If you're using a for loop, the code i wrote above is OK