Analyzing input from the user for string comparison

I am trying to create a code that activates when the user inputs a specific symbol or string. The issue is that it seems to be disregarding the if statements I have implemented.

Here is the challenge at hand: Develop a program that can determine the color of a chessboard square based on its Label and Rank. Input: On the first line, input L - the label On the second line, input R - the rank

let L = prompt();
let R = Number(prompt());
if (L == ("a", "c", "e", "g")) {
  if (R % 2 == 0) {
    /*if we are on a/c/e/g lines and the number is even the 
                         square is white*/
    console.log("light");
  } else {
    console.log("dark");
  } //else it is going to be odd therefore dark
} else if (L == ("b", "d", "f", "h")) { //opposite logic:
  if (R % 2 == 0) {
    console.log("dark");
  } else {
    console.log("light");
  }
}

The main issue I am facing is how to properly compare the two strings. I attempted utilizing various string methods, but it appears that I might be making a syntax error.

Answer №1

When comparing using ==, it's not as simple as you may think. You can either break your code into multiple or (||) statements or utilize an array:

Using Or:

var L = "e";
if (L == "a" || L == "c" || L == "e" || L == "g"){
    console.log("Using Or method");
}

Utilizing an array with the includes method:

var L = "c";
if (["a", "c", "e", "g"].includes(L)){
    console.log("Using includes method")
}

Another way is to use an array with the indexOf method:

var L = "g";
if (["a", "c", "e", "g"].indexOf(L) !== -1){
    console.log("Using indexOf method");
} 


To learn more about logical operators in JavaScript, visit:

https://javascript.info/logical-operators

Answer №2

("a","c","e","g") involves the use of comma operator, resulting in the evaluation to its final operand ("g" in this case). So

if(L==("a","c","e","g")){..}

is equivalent to

if(L == "g"){...}

You can utilize an array and then apply includes()

let L = prompt();
let R = Number(prompt());
if (["a", "c", "e", "g"].includes(L)) {
    if (R % 2 == 0) {
        console.log("light");
    } else {
        console.log("dark");
    } 
} else
if (["b", "d", "f", "h"].includes(L)) { 
    if (R % 2 == 0) {
        console.log("dark");
    } else {
        console.log("light");
    }
}

You can simplify your code significantly by creating an array containing both sets of letters, and then adding the index of the array where L is present to R

let L = prompt();
let R = Number(prompt());

const arr = [['a','c','e','g'],['b','d','f','h']];


if((R + (arr.findIndex(a => a.includes(L)))) % 2 === 0) console.log('white');
else console.log('black');

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

Using a div in React to create a vertical gap between two React elements

I am working with two React Components in my project - the Right Column and the Left Column. I am trying to create space between them using a div tag. Currently, my setup in the App.js file looks like this: import React from 'react'; import LeftC ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

What is the best approach to storing and retrieving special characters ('+<>$") from a textfield into a database using PHP?

I have a form where users can enter a personal message with a subject. The data entered in the textarea is passed to a Javascript/jQuery function, which then sends it to a PHP file for storage in a database. However, I am encountering issues when special c ...

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

Use npm to include a new dependency from the current dependency structure

I am currently working on a Vue application that utilizes both vuetable-2 and vue-axios. In my app.js file, I have the following imports: import Vue from 'vue' import VueMaterial from 'vue-material' import axios from 'axios' ...

Unable to modify the chosen option within a select dropdown

I am trying to change the selected option of a select element using jQuery, but I can't seem to make it work. Here is the code I have: $("#ID option[value=grpValue]").prop('selected', 'selected').change(); If I manually type in a ...

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

Is it possible to use a component created in the newest version of Angular in apps developed with older versions of Angular?

I am interested in developing a component using the most recent version of Angular. However, my intention is to use this component in two distinct Angular applications - one created with Angular 6 and another with Angular 10. Is it feasible to achieve this ...

The table is unable to properly display the array data

My code includes an AJAX function that sends a GET request to an API and receives data in the format shown below: { "firstname": "John", "lastname": "Doe", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

When launching JQuery UI Tabs in a new browser tab using ajax, the HTML from the ajax response will be immediately shown

I am currently in the process of upgrading from JQuery UI 1.8.14 to JQuery UI 1.10. Previously, when using v1.8.14 code, opening a tab in a new browser tab would cause the entire page to reload, activating the default tab (tabIndex=0). However, I am faci ...

What is the best method to divide a string, enclose it within a span tag, and generate fresh code using jQuery?

Is there a way to separate multiple links, enclose them in a span tag, and then iterate through them to display them back within the a tag? I have managed to split all the dates into the dateArr array, but I need help looping through them to output each on ...

What is the proper way to retrieve the JSON data?

How can I retrieve data from another table to use in a detail view if the value returned by the getData method is null? <th data-field="id" data-detail-formatter="DetailFormatter">ID</th> <th data-field="prefix&quo ...

Could someone please help me identify the mistake in this code? I recently created a new class, imported it into a .ts file, and then proceeded to define

Upon checking the console, an error message appeared stating that Recipe was not defined. To resolve this issue, I made sure to include the necessary class definition in a separate file at the end of my code. The import statement: import { Recipe } from ...

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

Is it possible for JavaScript to interact with elements that are created dynamically?

It's puzzling why the newly generated elements remain unseen by the next function that is called. Any insights on how to address this issue would be greatly appreciated! Resolve: Incorporate async: false to deactivate the asynchronous feature in order ...

Work with JSON array objects

I am a novice in javascript and JSON. I have a requirement to process each JSON object, as shown in the example prototype below. Can someone please assist me in solving this problem? I need to log each room number given in the JSON sample below. How can I ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...