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

Encountering an issue while attempting to extract an ACF field in WordPress using JavaScript

When I write the following code, everything works fine: <script> $(document).ready(function(){ var user_id = '<?php echo get_current_user_id(); ?>'; // This is working var subject = "<?php echo the_field('subject ...

Having trouble getting your custom Angular directive to function properly with dynamically changing images?

Currently in the process of developing a custom directive for AngularJs that involves an image rotator based on a Jquery Plugin I created, you can check it out here Below is the code snippet for my directive: .directive('imageRotator', function ...

Maintaining aspect ratio of canvas while ensuring responsiveness

Currently, I am working on a drawing app and have come across an issue that has been challenging for me to resolve. The dilemma lies in resizing the canvas of sketches from the original resolution of 1280 x 720 to the maximum size possible upon opening the ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Toggle a button with javascript

My setup involves two switches: <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="switch1" checked> <label class="onoffswitch-label" for="switch1"> <span class="onoffswitch-inner"></span> <span ...

Revamping Slideshows: Bringing CSS Animation to JavaScript

/* JavaScript */ var slides=0; var array=new Array('background.jpg','banner.jpg','image.jpg'); var length=array.length-1; $(document).ready( function(){ setInterval(function(){ slides++; ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

Updating state within an eventListener in useEffect with an empty array does not trigger a re-render

This text is unique because I tried to enhance it with an updater function that did not yield the desired result. Here is the code snippet: const [counter, setCounter] = useState(0); useEffect(()=> { const fetchSessions =async ()=> ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Leveraging a fetch request response in componentDidMount to power a subsequent request within a React-Redux component

I am currently facing a challenge with a component that triggers a fetch request (in redux) on componentDidMount. I now need to make another fetch request in the same component using the response data from the first fetch, and ideally before rendering. Si ...

"Complete with Style: Expand Your Horizons with Material-UI

The Autocomplete feature in Material UI is not expanding to the full width of the TextField element. Any suggestions on how to fix this issue? ...

Using Google Apps Script to upload a text file to Google Drive

It seems like uploading a file should be straightforward. However, I'm struggling with understanding blobs. function createFileUploader() { var app = UiApp.createApplication(); var panel = app.createVerticalPanel().setId('panel'); v ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Tips for creating a vertical drawer using jQuery and CSS

Hello, I am currently working on developing a drawer component using Ember.js. If you want to view the progress so far, feel free to check out this jsbin http://jsbin.com/wulija/8/edit My goal is to have the drawer look like the following initially: +--- ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the first t ...