0

First off, new to Javascript ... trying to write good code! As a test for the app I am writing, I want to have a user's name input via prompt checked against an array that will enable user to keep going or prevent user from doing so.

I can get includes to filter properly when I assign a value to a variable:

var name, excluded_Persons;
var name = "jim"

function denyEntry () {

var excluded_Persons = ["bob", "jim"];

    if (excluded_Persons.includes(name)) {
    alert("You may not enter!!");
    enterName ();
    }

    else {
        allowEntry ();
    }
}
denyEntry ();

function allowEntry () {

    alert("You have been granted access!!");
}

returns "You may not enter!" However, when I include the function enabling the user to input a name,

    var name, excluded_Persons;

function enterName () {
    var name = prompt("What is your name?").toLowerCase();
    }

enterName ();

function denyEntry () {

    var excluded_Persons = ["bob", "jim"];

    if (excluded_Persons.includes(name)) {
    alert("You may not enter!!");
    enterName ();
    }

    else {
        allowEntry ();
    }

}

denyEntry ();

any name the user inputs (including "bob" and "jim") returns "You have been granted access!" The includes function is being bypassed.

Am I missing an argument in either the enterName function or the denyEntry function?

4
  • You should stop where you are and consider using a server side solution for this. Dealing with user access client side is way to easy to bypass. Commented Jun 15, 2018 at 17:38
  • Remove var in front of the variable name that's inside the enterName function. Commented Jun 15, 2018 at 17:38
  • @devlincarnate, thanks! Commented Jun 15, 2018 at 18:58
  • @LGSon, the app I'm working on doesn't actually involve authentication. If it did I totally agree with you. Commented Jun 15, 2018 at 19:01

1 Answer 1

1

You are redeclaring the Name inside function enterName() so its scope is limited to only that function. Make name global variable:

var name, excluded_Persons;

function enterName () {
     name = prompt("What is your name?").toLowerCase();
}

enterName ();

function denyEntry () {

    var excluded_Persons = ["bob", "jim"];
    console.log(name);
    if (excluded_Persons.includes(name)) {
    alert("You may not enter!!");
    enterName ();
    }

    else {
        allowEntry ();
    }

}

denyEntry ();

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

2 Comments

The first line declares name as a global. The problem is that there's a local variable of the same name inside the enterName function.
Closer. You have var name declared twice. Remove the second one.

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.