My son is turning 10 and he's learning JavaScript. I am creating a birthday tarp for him and I want to use my below code. Do you think you can short it? Your input will be highly appreciated.
In my tarp, I will get rid of and
let age = 10, ten = 10;
while (true) {
if (age == ten) {
alert('Happy 10th Birthday, son!');
break;
} else {
age++;
}
}
let age = 10;
while (true) {
if (age === 10) alert('Happy 10th Birthday, son!');
else age++;
}
If you're looking for something succinct but decorative, perhaps
let age = 0; // birthdate mm/dd/yyyy
while (age < 10) {
age++
}
alert(`Happy ${age}th birthday, son!`);
The while condition keeps getting tested until it returns false; so it'll keep running as long as age is less than 10. Its last iteration happens at age == 9: 9 is less than 10, so it calls age++, now age is 10. It tries the why condition again, age is 10, so no longer less than 10, so it skips ahead to the alert.
Here's a runnable example with a lot more detail so you can see what it's doing:
let age = 0;
// Pulling "age < 10" out into a function, so it can log what it's doing:
let checkAge = (age) => {
console.log(`Checking if ${age} < 10: ${age < 10}`);
return age < 10;
}
while (checkAge(age)) {
console.log(`Will add 1 to ${age}`);
age++;
console.log(`Age is now ${age}`);
}
console.log(`Happy ${age}th birthday, son!`);
Maybe this? Happy new year for your son :')
let age = 0;
while (age < 10) {
age++;
}
alert('Happy 10th Birthday, son!');