JavaScript While Loop with if-else if-else and counter

263
June 10, 2017, at 6:03 PM

I am new to JavaScript. I was taking some tutorials and tried to make a code which printed the multiples of 10 up to 120. It should not print 100, and show a message after 120.But for some reason, it doesn't work. On running the code, nothing on the page is displayed, not even other text. Please Help!

var z = 10;
while (z<150){
    if (z==100){
        document.write("Cannot print 100!");
        continue;
    }
    else if (z==130){
        document.write("Cannot print after 120!");
        break;
    }
    document.write(z+"<br>");
    z+=10;
}
Answer 1

Because iterator won't to beyong 90 as condition says in while loop. Make that condition z<=120.

Or

while(z <= 120) {
  if (z==100) {
    // cant print 100 z = z + 10;
    continue;
  }
  // print z
  z = z + 10;
}
Answer 2

1) You should ensure to declare the variable (var z = 0;) or you will encounter an "undefined variable" error.

2) The while loop condition is wrong, because your loop will never print 110 and 120 with z < 100. You can set while(z < 130) or while(true).

3) I also suggest you to change your break condition from z == 130 to z >= 130, so you're not going into an endless loop in case you decide to change counter increment.

4) Finally, it is a common mistake in while loops to place counter increment in wrong line. In this case when z reaches 100 it will never go on.

var z = 0; 
while (z < 130){ 
    z+=10; 
 
    if (z==100){ 
        console.log("Cannot print 100!"); 
        continue; 
    } 
    else if (z>=130){ 
        console.log("Cannot print after 120!"); 
        break; 
    } 
    console.log(z); 
}

Answer 3
for(var i=10;i<=120;i+=10){
   if(i===100){
        continue;
   }
   document.write(i+'\n');
}
or with while loop
var j=10;
while(j<=120){
     if(j===100){
         j+=10;
         continue;
     }
     document.write(j+'\n');
     j+=10;
}
READ ALSO
Spring boot and react running on tomcat

Spring boot and react running on tomcat

I am developing Spring boot application with react client using gradleI am new to all these technologies

494
How to load webpage elements in specific order - header, sidebar, content, footer ?

How to load webpage elements in specific order - header, sidebar, content, footer ?

I'm wondering if it's possible to load page elements in a specific order for a sake of user experience optimisation

230
Display image using angular 2

Display image using angular 2

I am very new to angular 2 I am stuck here where i have to display an image for which I'm using relative path­­­­­­­­­­­­­­­­­­­­

547
appending a div to a classname using javascript

appending a div to a classname using javascript

It throws an error that wrapper is not defined, it only worked when I used documentbody instead of wrapper, but I want to append them divs to the wrapper div any suggestions ?

325