Print even number in JavaScript

I want to print all even numbers between 10 and 40. But what’s wrong with my code?

code:

console.log("Print all even number between 10 and 40");
var num = 10;
while(num%2 == 0 && num < 40){
	console.log(num);
	num ++;
};

When I run in on console it’s just print 10 :frowning:

Notice what happens when num is incremented to 11, does the while condition is still met? If not then the loop will end.

2 Likes

Oh ya :stuck_out_tongue:
Now it’s working well!

console.log("Print all even number between 10 and 40");
var num = 10;
while(num <= 40){
	if(num%2 === 0){
			console.log(num);
		};
	num ++;
};

Thank you!

2 Likes

Also if you want to include the number 40 I would add <=

1 Like

Let’s follow the code…

  1. num = 10
    num%2==0(true) && num<40(true) => true (Continue to the loop)
    - (logs num to screen)
    - num = 11
  2. num%2==0(false) && num<40(false) =>false (exit out of loop)
    Exit Program
1 Like

It’s more efficient :relaxed:

var num = 10;
while(num <= 40){
	console.log(num);
	num += 2;
};
1 Like