Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this cause an infinite while loop?

I'm completely new to coding and have started learning JavaScript recently. I don't understand why the following code causes an infinite loop. Why does the birthday(myAge) function not work within the loop to make the condition (myAge < 23) false?

var myAge = 22
var birthday = function(myAge){
    return(myAge + 1);
}

while (myAge < 23){
    console.log("You're only 22");
    birthday(myAge)
}
like image 728
JosephByrne Avatar asked Jul 22 '26 10:07

JosephByrne


1 Answers

Because you are not modifying myAge in any way. Your function is simply returning myAge + 1.

Try assigning the return value back to myAge:

while (myAge < 23){
    console.log("You're only 22");
    myAge = birthday(myAge);
}

Or alternatively, if you remove the function parameter, then the name myAge within the function will refer to the global variable, and you can modify it directly:

var myAge = 22
var birthday = function(){
    return (myAge = myAge + 1); 
    // or return myAge += 1;
    // or return ++myAge;
}

while (myAge < 23){
    console.log("You're only 22");
    birthday();        // note, no need to pass any parameters
}
like image 126
p.s.w.g Avatar answered Jul 24 '26 00:07

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!