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

$set { "array.variable.value" :"newvalue"} utilize a different term besides "variable" or implement a new variable

When working with mongoose to store user data, one of the attributes is an array called items. In my additems.js file: const User = require('../models/User'); var array = user.items; array.indexOfObject = function (property, value) { ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

React to the animated scaling

I'm attempting to animate the scale of my react component. Although it seems straightforward, I've run into some issues while following a similar example from the React-Motion demos: var customComponent = () => { let newStyle = { scale: sprin ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

What is the process for converting x and y coordinates to align with a fixed display?

When I make an API call, I am receiving X and Y coordinates in the following format: x: "-0.0120956897735595703" y: "0.147876381874084473" To display these coordinates on my minimap images, I have set their display to be absolute. The "left" and "top" pr ...

Searching for a point within a specified range using Sequelize

I have a model called Location with a field named coordinates of type geometry. I'm looking to create a function that takes in latitude, longitude, and radius as parameters, and returns all locations within that radius (in meters). I attempted to foll ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

What emerging patterns can be observed in the security of client-side coding within the realm of web development

Keeping up with the constant flow of new frameworks and technologies can be overwhelming. One area that particularly interests me is client-side frameworks, such as AngularJS, Backbone, Knockout, jsviews, knockback, SPA... These are currently among the mos ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

Unleash the full potential of React and material-ui with the Raised Button feature - find out how to effortlessly keep all

This snippet showcases the code for my custom Buttons component: import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; const style = { button: { margin: 2, padding: 0, minWidth: 1, }, }; cons ...

Create a specific website link for searching on YouTube

Is there a way to generate a YouTube URL using JavaScript or PHP that searches for videos on a specific user account and displays the best title match at the top of the search results? This is the code I am currently using: <!DOCTYPE html> <head ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

What is the method for extracting a variable from a URL using JavaScript?

For instance, consider this URL- website.com/page/?var=20 I am looking to extract the "var" variable from the URL using JavaScript. By the way, my actual URL is- https://bipit2.pranaypro21292.repl.co/d21292auth/?code=pimWoHEuV7fgKEVQMTntRnzXqVla3G&gu ...