Reputation: 33
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?
Upvotes: 0
Views: 58
Reputation: 8239
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 ();
Upvotes: 1