DEV Community

Commodore-1
Commodore-1

Posted on

problem with this Javascript code, im noob btw

we have an array of numbers and we only want to print out the even ones: (part of code is missing in the note i have and i cant figure it out!)

let numbers = [1, 2, 3, 4, 5, 6]
var i = 0;
while (i 
    if (numbers[i] % 2 != 0) { continue; }    print(numbers[i]);}

Top comments (8)

Collapse
 
mranyx profile image
MrAnyx • Edited

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
 
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

Collapse
 
commodore1 profile image
Commodore-1

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
 
commodore1 profile image
Commodore-1

ah thank you man! appreciate it so much!

Collapse
 
commodore1 profile image
Commodore-1 • Edited

ok with all your inputs i think i found the right solution for this, in my original notes it was asking with while loops and continue statement get the all the even numbers within an array:

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

There can be many solutions for it .One of the solutions can be

             let numbers = [ 1, 2, 3, 4, 5, 6 ];
    var i = 0;
    while (numbers.length > 0) {
        if (numbers[i] % 2 == 0) {
            console.log(numbers[i]);
        }
        numbers.shift();
    }
Collapse
 
commodore1 profile image
Commodore-1

i posted this thinking problem is so basic that probably no one would even reply, feels good :)