I'm building a simple registration website, and I'm trying to ensure that if a user enters an age under 18, they get a single alert saying, "Sorry, you're still too young to register." However, when I test the function, the alert pops up twice even though I think I've only called the checkAge function once. Here's the code I'm working with:
```
register();
function register() {
userName = prompt("What is your full name?", []);
age = prompt("What is your age?");
checkAge();
if (checkAge() == false) {
return;
}
}
function checkAge() {
if (age < 18) {
alert("Sorry, you're still too young to register.");
userName = "";
age = "";
return false;
} else {
return true;
}
}
```
Can someone help me figure out what I did wrong?
3 Answers
You’re calling checkAge() twice: the first call is standalone and doesn’t save the result, then it's used again in the if statement, which calls it again! To resolve this:
- Either save the first call to a variable and check that variable later, or
- Just use the check in the if condition alone.
This will help you avoid the double alert and keep your code clean! Also, it’s best practice to separate functionality, so maybe move the alert out of checkAge so that it only checks the age.
You're calling the checkAge function twice. The first time is just a standalone call, but then you also call it again in the if statement. This is why the alert pops up twice. You can fix this in a couple of ways:
1. Save the result of the first call into a variable and check that variable in the if condition instead of calling function again.
2. Just remove the standalone checkAge() call and rely solely on the if statement to do the checking.
Totally agree! It also makes it easier to manage the logic as you build more features.
Absolutely! It's a common mistake for beginners to make. I recommend changing the first instance to something like `let isOfAge = checkAge();` and use `isOfAge` in your if statement. That way you're storing the result of the check without needing to call the function multiple times.
That’s a good point! If you want it to work seamlessly, definitely save the result from checking age into a variable. It keeps your code cleaner and avoids redundant calls.