JavaScript's includes method fails to verify input against the array

Just starting out with Javascript and striving to write clean code! To test my app, I aim to have a user's name input via prompt checked against an array for validation purposes.

When I hardcode the value of a variable, the includes function filters as expected:

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!!");

}

This setup correctly displays "You may not enter!" However, the issue arises when incorporating a function that allows users to input their 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();

Surprisingly, regardless of the inputted name (even "bob" or "jim"), the message displayed is "You have been granted access!" It seems like the includes function is being disregarded.

Could there be a missing argument in either the enterName or denyEntry functions?

Answer №1

To ensure that the variable Name is accessible throughout your code, it is important to declare it as a global variable instead of redeclaring it within the function enterName(). By making Name a global variable, you can use it across different functions and scopes.

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 ();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

Terminate the connection with nginx abruptly

Is there a way for nginx to immediately close the TCP connection once the request has been completed? ...

Looking for the right array syntax to validate the existence of `$options[self::SOME_PARAM]`

Currently, I am working with PHP. I am attempting to utilize a library that requires options in a certain method: public function __construct(array $options = array()) { (...) if (isset($options[self::SOME_PARAM])) { (...) } } When I ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

deciding on the axis for flipping a div with CSS

Is there a way to change the setting so that when using -webkit-transform: rotateY(180deg), it rotates from either the far left or right edge of the div, similar to how a door swings open? ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...

Seeking help with a Javascript regex inquiry

I am currently utilizing JavaScript regex for the following task: I have gathered the HTML content from a page and stored it within a string. Now, I aim to identify all URLs present on this page. For instance, if the document includes-- <script src = ...

jQuery sidebar with a fixed position

Is there a way to implement a sidebar menu feature using jQuery that reappears on the left as the user scrolls down the page? You can see an example sidebar menu here. ...

Developing an interactive graph with Django and harnessing the power of chart.js

I’m currently navigating the world of Django as a newcomer. My current project involves conducting sentiment analysis on real-time user tweets using the Twitter API. I've successfully analyzed and displayed the sentiments extracted from these tweets ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Is there a way to return two separate functions within a single function that can be rendered as two distinct components in a React application without one function overriding the other?

I'm currently working on a react header that uses conditional rendering to show different elements based on the URL or user login status. However, I'm facing an issue where only one button is being rendered instead of two side by side in my defau ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

Error in Node.js: [Error: Query parameter should not be empty]

I've been recently focusing on a project that involves sending the required name to my profile.js file using a POST request. However, whenever I try to access console.log(req.body.bookName) (as the data being sent is named bookName), it shows an error ...

Using Vue.js to send user input data to a different page and trigger a method for submission

I am seeking assistance with my first question and hope to receive your support. In my setup, I have a catalogue page that includes a keyword search function and a main page with a search bar. My objective is to automatically redirect any submission from ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

What are the steps involved in converting a MERN application into a desktop application?

As a beginner in front-end application development, I recently created a MERN application in React with separate frontend and backend parts. Everything is working smoothly, but now I want to convert it into a desktop application that can run independently ...

What are some ways to personalize column design when a Kendo grid column is automatically created?

I am populating the Kendo grid with data using JavaScript: var dataSource = new kendo.data.DataSource({ transport: { read: { url: "@Url.Action("GetProductList", "Home")", type: "POST&qu ...

Having trouble with updating links in HTML pages?

I'm having trouble updating all the links in my HTML file. The code I have isn't working as expected. var fs = require('fs'); fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){ if(!err){ html = ...