Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal.

var person = ["Sam", "John", "Mary", "Liz"];
var searchedName = prompt("Enter name");
var resultMessage = "";

for (index in person) {
  var currentName = person[index];

  if (currentName === searchedName){ 
    resultMessage = "Found Person";
  } else {
    resultMessage = "No match found!";
  }
}

console.log(resultMessage);

Answer №1

If you are looking to find a specific person in an array, you can utilize the Array#some method.

var people = ["Sam", "John", "Mary", "Liz"];

var firstName = prompt("Please enter a name");

var personFound = people.some(person => person === firstName);
var message = personFound ? "Person Found" : "No match found!";

console.log(message);

This code snippet essentially checks if at least one person in the 'people' array matches the input name provided by the user.

Answer №2

Try this out...

const people = ["Sam", "John", "Mary", "Liz"];
const inputName = prompt("Enter a name");
let outputMessage = "";

people.forEach((name) => {
    if (inputName.toLowerCase() === name.toLowerCase()) {
      outputMessage = "Person found";
      return false; 
    } else {
      outputMessage = "No match found!";
    }       
});

console.log(outputMessage);

This code has been tested and works properly.

Answer №3

I made some modifications to your code, hopefully it will now function as intended.

var individuals = ["Sam", "John", "Mary", "Liz"];

var userInput = prompt("Please enter a name");

var outputMessage = "";

for (name in individuals) {

//    var firstName = individuals[name];

        if (name.localeCompare(userInput)) {

        outputMessage = "No match found!";
    } else
        {

        outputMessage = "Person Found";

    }

}

console.log(outputMessage);

Answer №4

var members = ["Jake", "Sarah", "Michael", "Emily"];
var searchName = prompt("Please enter a name:");
var result;

for (var i in members) {
  console.log(searchName);
  console.log(members[i]);

  if (searchName === members[i]) {
    result = "Found Member";
  } else {
    result = "Not Found";
  }

  console.log(result);
}

Here's a simple way to check if a specific string is present in an array:

console.log(members.includes(searchName)); // This returns true or false

Answer №5

Make sure to delete the line that reads var firstName = person[x];

View a working demonstration here

for (var x in person) {

//   var firstName = person[x];

if (firstName == person[x])
  {

      message = "Person Found";
      break;
  }

else 
  {
      message = "Not Found";
  }

//console.log(firstName);

} 

console.log(message);

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 background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

When attempting to submit information to a database table, I encounter an error in the browser console: "Uncaught (in promise) Error: Request failed with status code 404."

In my React Node project's login page, I am encountering the following issue. Despite thoroughly reviewing my code after each execution, the error persists. My goal is to pass data from the login page into my MySQL database; this marks the initial sta ...

Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't becom ...

Tips for preserving input field data in an AngularJS scope variable

I am having trouble storing textbox values in my 'Values' variable. When I enter values in the textboxes, it seems to be getting the hard-coded values instead. Can someone please help me with this AngularJS issue as I am new to it? Here is the co ...

Implementing CSS styles with jQuery

Looking for a way to dynamically add CSS attributes to different form elements like text fields, text areas, checkboxes, and dropdowns? There's also a separate block that lists possible CSS properties such as font, font-style, width, and padding. What ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...

What is the best way to set the active class on the initial tab that is determined dynamically rather than a static tab in Angular?

I'm currently facing a problem with ui-bootstrap's tabsets. I have one tab that is static (Other) and the rest are dynamically added using ng-repeat. The issue I'm having is that I can't seem to make the first dynamically loaded tab act ...

Troubleshooting the "Failed to mount component" error in Vue: fixing template or render function definition issues

Struggling with writing a Vue component, encountering the issue: Failed to mount component: template or render function not defined. Tried various fixes like adding default when importing the component, but none of them seem to work. My component code is i ...

Choose2 - Dynamic search with auto-complete - keep track of previous searches

Currently, I am utilizing Select2 version 3.5.1 and have successfully implemented remote data loading with the plugin. However, I have a query regarding enhancing the search functionality. Below is a step-by-step explanation of what I aim to achieve: Cre ...

Variable fails to be assigned to Element

Having trouble updating the innerHTML attribute for both elements with ids containDiv and status. For some reason, it only changes containDiv but not status. The console shows an error "Cannot set property innerHTML of undefined", indicating that the eleme ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Switch between class and slider photos

I am currently having an issue toggling the class. Here is the code I am working with: http://jsfiddle.net/h1x52v5b/2/ The problem arises when trying to remove a class from the first child of Ul. I initially set it up like this: var len=titles.length, ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Exploring the functionality of custom hooks and context in asynchronous methods using React Testing Library

I'm currently testing a hook that utilizes a context underneath for functionality This is how the hook is structured: const useConfirmation = () => { const { openDialog } = useContext(ConfirmationContext); const getConfirmation = ({ ...option ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...