Can someone help me with a while loop


#1


When to 'While & when to 'For'


Hello, I am new with this JavaScript,
I have a problem which is this code right bellow, it wont print "I'm doing a while loop" in the console.
Thanks,


r loop = 4;
var A = 1

var whileLoop = function() {
    while(A) {
        if(loop > 0) {
            console.log ("I'm doing a while loop");
            loop+= -1;
        }
        else {
            var A = 0:
        };
    };
};


#2

I'm going to add comments to show what I see:

r loop = 4; //I think you meant: var loop = 4;
var A = 1 //missing a semicolon at the end

var whileLoop = function() {
    while(A) { 
        if(loop > 0) {
            console.log ("I'm doing a while loop");
            loop+= -1; // this could be simplified to: loop--;
        }
        else {
            var A = 0: //there is a colon instead of a semicolon
        };
    };
}; // you did not actually call the function, insert: whileLoop();

The final result:

var loop = 4;
var A = 1; 

var whileLoop = function() {
    while(A) { 
        if(loop > 0) {
            console.log("I'm doing a while loop");
            loop--;
        }
        else {
            A = 0;
        };
    };
}; whileLoop();

#3

This creates an infinite loop since nothing is going to change boolean true to boolean false. Maybe try using a variable with a boolean value that can be changed after the loop runs?


#4

@biff75 My bad, I substituted true for A when I was playing around in my console. I'll edit my post, thanks for pointing that out.


#5

I didn't catch it until it ran through https://repl.it :slight_smile:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.