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)
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With