JavaScript code for when either "a," "b," or "c" is true, but not all of them

Hey there, I'm just getting started with JavaScript! I'm working on creating a syntax to determine if only one of three variables is present.

if a and (not b or not c) or b and (not a or not c) or c and (not a or not b)

Answer №1

Give this a try:

if ((x || y || z) && !(x && y && z)) {

}

Check out this demonstration:

function checkConditions(x, y, z, output){
  if ((x || y || z) && !(x && y && z)) {
    console.log(output)
  }
}

checkConditions(true, false, false, 'One true');
checkConditions(true, true, false, 'Two true');
checkConditions(true, true, true, 'All true'); // Shouldn't print anything

Answer №2

Transform them into boolean values, then add them together and verify that the total equals 1. (true will be converted to 1; false will be converted to 0.)

if (Number(Boolean(a)) + Number(Boolean(b)) + Number(Boolean(c)) === 1) {
  // ...
}

alternatively

const sum = [a, b, c].reduce((total, item) => total + Number(Boolean(item)), 0);
if (sum === 1) {
  // ...
}

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

How to send a server-side type to an ASP.NET webform to be consumed by JavaScript

Currently, I am working on passing a predefined Type (List) to an asp.net web form that needs to be recognized by JavaScript when the page loads. The sample data I am generating appears like this: protected List<MapCoords> createCoordinateList() ...

When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue: const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im; re.test(control.valu ...

Juicer- Setting restrictions on the frequency of posts

How can I limit the number of posts displayed using the react-juicer-feed component? import { Feed } from 'react-juicer-feed'; const MyFeed = () => { return ( <Feed feedId="<feed-id>" perPage={3} /> ...

What could be causing my chosen value to remain unchanged after being copied from a controller?

I am struggling with controlling a <select> element using both ng-model and ng-options: <select ng-model="user.option" ng-options="value.label for (key, value) in data.options"> <option value="">Select value</option> ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...

Create a dynamic animation of a line being drawn in Three.js

I am trying to create an animation of a Lorenz attractor using Three.js. I found a helpful YouTube tutorial that serves as a guide for this project. You can view a snippet of my current progress here: // SETTING UP THE SCENE // ------------------------ ...

"Ensure div remains at the bottom of the page even while

In order to implement a feature where the menu sticks to the top when scrolling down, you can use the following JS code. You can view a live example of this functionality on this Plunker by widening the preview window to see the columns side by side. wi ...

Create a personalized and distinct name following the submission of data into multiple text fields either through Nuxt/Vue or by utilizing pure JavaScript

In my new app, users can register packages and then participate in a ballot session where the package will be assigned to someone else. To make this process smoother, I want each ballot session or box to have a unique Ballot ID attached to it. For example ...

Utilize Vue.js to incorporate an external JavaScript file into your project

Currently, I am utilizing Vue.js 2.0 and facing an issue with referencing an external JavaScript file in my project. The index.html file contains the following script: <script type='text/javascript' src='https://d1bxh8uas1mnw7.cloudfro ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

The construction was unsuccessful due to errors in the webpack process

I encountered a sudden error in my Next.js app. Is there any solution available to resolve this issue? ./pages/_app.tsx Error: [BABEL] C:\Projects\skribeNew\app-web\pages\_app.tsx: You provided us with a visitor for the node type T ...

The element is automatically assigned an 'any' type due to the inability to use a 'string' type expression to index the 'DataType' type

Encountering an issue where row[header.key] is displaying the error message Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DataType'. I prefer not to use type:any and ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

Next/image is encountering an error due to an invalid Element type being generated

Trying to utilize the next/image feature to display an SVG image is causing me some trouble. Every time I attempt this, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...

Tips for anticipating a string that begins with a particular variable

One of the challenges I'm facing involves a simple function that creates a string from a complex object. To illustrate, consider the following implementation: public generateMessage(property: string): string { return `${property} more text.`; } ...

Tracking hits with Node.JS Connect

Feeling a bit bored, I decided to create a connection counter (shown below) that logs each client connection as two different connections. Can anyone explain why this unexpected behavior is occurring? var http = require('http'); var count = 0; ...