0

I would be forever grateful if you could enlighten me how to get it to work. Currently when I run it it gives the alert upon the first entered username.

let userName1;
let userName2;
let userName3;

alcoholAgeCheck();
alcoholAgeCheck(userName2);
alcoholAgeCheck(userName3);

function alcoholAgeCheck() {
  userName1 = prompt('Enter name');

  if (userName1 === userName2 || userName1 === userName3) {
    alert('Sorry, you may only use the same name once');
  } else if (userName2 === userName1 || userName2 === userName3) {
    alert('Sorry, you may only use the same name once');
  }
}

3
  • If you don't give a value to userName2 and userName3, than userName2 === userName3 will always be valid. Commented Oct 4, 2021 at 22:52
  • @Gerard What value do I give them? I just want to find a way to have it run once with userName1, once with userName2 and once with userName3 Commented Oct 4, 2021 at 22:54
  • Taking your question at face value, the code you're looking for is: jsfiddle.net/1p3q8axw However that is a bad approach for multiple reasons and you shouldn't use it at all. Commented Oct 4, 2021 at 23:24

1 Answer 1

3

Save all the previous inputs in a variable, and check whether the new input is in the set.

const userNames = new Set();

function alcoholAgeCheck() {
  userName = prompt('Enter name');
  if (userNames.has(userName)) {
    alert('Sorry, you may only use the same name once');
  } else {
    userNames.add(userName);
  }
}

alcoholAgeCheck();
alcoholAgeCheck();
alcoholAgeCheck();
console.log(Array.from(userNames));

Sign up to request clarification or add additional context in comments.

5 Comments

The only thing I would add to this is a console.log() afterward so the OP can see what you did here. Great solution.
@Barmar Hi Barmar, thank you for this solution. I've yet learned new Set and Has. Is there a way for me to write it with my code, with just giving values to the variables?
@helpme No, because that's not how function parameters work in JS. What you're trying to do is called "pass by reference" and possible in for instance C, but not in JS. In JS, it's always "pass by value".
Why would one pick a Set over a simple Array here?
@connexo Searching a set is more efficient. But for small quantities, an array and .includes() would be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.