Why is my alert showing up twice in JavaScript?

0
0
Asked By CuriousCat23 On

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

Answered By TechWizard99 On

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.

Answered By CodeNinja45 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.