I'm building a basic registration website, and I want to show an alert if the user enters an age under 18, saying "Sorry, you're still too young to register." However, the alert pops up twice when I test it, despite only calling the checkAge function once. Here's the relevant part of my code:
```javascript
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;
}
}
```
What am I doing wrong?
2 Answers
You're actually calling `checkAge()` twice in your `register()` function. The first time you call it is standalone, and then you call it again in the `if` statement. Here's what you should do: save the result of your first call to a variable, like this:
```javascript
let isOfAge = checkAge();
if (!isOfAge) {
return;
}
```
This way, you avoid calling the function again during your condition check.
It’s a common mistake! You're invoking `checkAge()` on its own, then again in your `if` condition. If you don't want to repeat the call, you could simply remove the first call to `checkAge()`. Just use the second call, that way you get rid of the extra alert. Also, consider moving the alert out of the `checkAge()` function to keep it focused just on checking the age.
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String