Tips for using "if not equal" with multiple items in JavaScript

I have a simple question that I've been thinking about. Is there a way to accomplish the following:

If i is not equal to 1, 2, or 3, then alert('yes');

Can we achieve it using the following code:

if (!(i==1&2&3)) { alert('yes')}

Instead of the following longer version:

if (!((i==1) || (i==2) || (i ==3) )) { alert('yes');}

Answer №1

Consider using a switch statement, but it's important to understand your goal.

switch (i) {
    case 1:
    case 2:
    case 3:
        break;
    default:
        alert(yes);
}

Another approach could be a lookup table like this:

var x = {
    1: true,
    2: true,
    3: true
};

if (!x[i]) {
    alert('yes');
}

If you prefer strict testing with just a few conditions, you can do:

if (i !== 1 && i !== 2 && i !== 3) {
    alert('yes');
}

Answer №2

Try creating an array and utilizing the indexOf() method

if([1,2,3].indexOf(i) < 0){
    alert('yes');
}

If the returned value is greater than -1, it indicates that i is present in the array.

This alternative approach:

if (!(i=1&2&3)) { alert('yes')}

Might not achieve your intended outcome as 1&2&3 represents a bitwise AND operation, and there is only one = operator being used.

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

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

What is the best way to display an empty record in a table utilizing JSON?

I am facing an issue with parsing a JSON file that contains information about movie nominees and their win probabilities. The goal is to display this data in a table where the WinType field determines whether the nominee has won or been nominated for an aw ...

Examining - Assessing the Link (next/link)

I am currently working on writing unit tests to verify the functionality of my navigation links. Here is a snippet from my MainNavigation.js file: import Link from 'next/link'; const MainNavigation = () => { return ( <header> ...

Include a new variable in a JavaScript email template

Is there a way to include the variable bob in the body of an email? var bob; function sendMail() { var link = "mailto:YourEmailHere" + "?cc=" + "&subject=App Build Link Buit With MWFPRO's App Build Tool" + "&body=Hi ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

Is there a way to refresh an Angular component in Storybook using observables or subjects?

When I attempt to update my Angular component using a subject in Storybook by calling subject.next(false), I encounter an issue. The instance property of the component updates, but it does not reflect in the canvas panel. Here is my loading component: @Co ...

Displaying temporary data and removing it from an HTML table: Tips and Tricks

There are three input boxes and a button below them. When the button is clicked, I would like the input data to appear in an HTML table where I can delete records. I would greatly appreciate any assistance. Thank you in advance. ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...

Customized content is delivered to every client in real-time through Meteor

I am currently working on creating a multiplayer snake game using three.js and meteor. So far, it allows one player to control one out of the three snakes available. However, there is an issue where players cannot see each other's movements on their s ...

Error in three.js library: "Undefined variable 'v' causing a TypeError" while creating a custom geometry

I am attempting to create my own custom geometry using three.js. However, I encounter an error when trying to define it with the following code: geometry = new THREE.FreeWallGeometry( 3, 5 ); The error message "TypeError: v is undefined" originates from ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

Ensuring the canvas fits perfectly within its parent div

I am attempting to adjust my canvas to fit inside a div. // Make the Canvas Responsive window.onload = function(){ wih = window.innerHeight; wiw = window.innerWidth; } window.onresize = function(){ wih = window.innerHeight; wiw = window.innerWidth; } // ...

Ways to refresh the information in local storage when new data has been chosen

I am in the process of developing an online ordering system where users can select items and add them to their shopping carts. To store the selected items, I am utilizing local storage so that they can be retrieved on the next page. One issue I am current ...

Customize the inline click event using jQuery

I have a navigation with links that resemble the following: <a id="navform" href="#" tabindex="-1" onclick="mojarra.ab(this,event,'action','@form','content');return false" class=" ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

Disappear element after a brief moment

What is the best way to temporarily hide an element and then have it reappear after a second? var targetElement = document.getElementById("myElement"); targetElement.onclick = function() { this.style.display = "none"; setTimeout(function(){ ...

The multiplayer game is experiencing significant delays due to issues with the websocket server

While developing a multiplayer game, I have implemented a WebSocket Server to facilitate communication between clients. However, I am experiencing sporadic delays in message delivery from the server to the client. These delays can be significant, sometimes ...

Incorporate a minor detail within the H1 using jQuery

I am attempting to update the text within an h1 tag that includes a small element inside it. However, despite successfully changing the main content when the button is clicked, the styling for the small element is not being applied. Here is the HTML code: ...

Dealing with a JavaScript Problem on Wordpress Using AJAX

Struggling with transitioning a website from Drupal to WordPress, I encountered an issue with a page that utilizes AJAX. A user followed a tutorial on implementing AJAX using JavaScript, PHP, and MySQL. Even though the AJAX functionality works fine on Drup ...