Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? And if it is allowed, in which version of JS was this functionality added and what is the name of this type of shortcut comparison?

const exampleVar: 'a' | 'b' | 'c' | 'd' = 'a'

// Checking if exampleVar is 'a' or 'b'
if ( exampleVar === ('a' || 'b') ) {
  console.log('Yay!');
} else {
  console.log("Not 'a' or 'b' - Boo!");
}

I would expect this to return true if exampleVar is 'a' or 'b'. It seems to work in console in modern browsers, so my main questions are where can this be safely used and what is this technique called so I can verify its support on platforms like CanIUse.

Answer №1

Sorry, but that approach won't give you the desired outcome.

exampleVar === ( 'a' || 'b') actually translates to exampleVar === 'a'

The or operator returns the right-hand value if the left-hand value is falsy.

You might be closer to what you want with something like this:

if(['a', 'b'].includes(exampleVar)) {
  ...
}

Answer №2

To implement different outcomes based on a variable, you can utilize the switch statement:

switch(userChoice) {
case 'optionA':
case 'optionB':
  console.log('Great choice!');
  break;
case 'optionC':
  console.log('Another excellent choice!');
  break;
default:
  console.log("Not option A or B or C - Try again!");
}

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

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Returning a React component only under certain conditions to meet the requirements of a Suspense fallback mechanism

Whenever I return a component (using nextjs 13) that depends on fetched data, I usually conditionally render elements to ensure that the values are available: TableComponent: export const Table = ({ ...props }) => { const [tableEvents, setTableEve ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... https://i.sstatic.net/FFCRW.png My goal is to show the loading indicator when any action, like deleting an item or changing qua ...

Utilizing AngularJS "controller as" syntax within templates

Recently diving into the AngularJS world, I embarked on setting up a simple laravel/angular JWT authentication by following this specific tutorial. My goal is to utilize the "Controller As" syntax instead of relying on $scope as instructed in the tutorial ...

Create your own Angular control - rate stars - with dynamic input values

<div class="rating"> <div style="display: inline-block" *ngFor="let starred of stars; let i = index" (click)="rate(i + (starred ? (value > i + 1 ? 1 : 0) : 1))"> <ng-container *ngIf="starred; else noStar"><mat-icon class=" ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

Did you manage to discover a foolproof method for the `filesystem:` URL protocol?

The article on hacks.mozilla.com discussing the FileSystem API highlights an interesting capability not previously mentioned. The specification introduces a new filesystem: URL scheme, enabling the loading of file contents stored using the FileSystem API. ...

Establish validation parameters for uploading multiple files

I need to implement client-side validation for my FileUpload control to ensure that users can only select up to 10 images. While I already have the server-side code in place, I now want to add client-side validation as well. Sample Code: <asp:FileUplo ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Merging classes from several files into a unified namespace in typescript

When working with typescript, my goal is to instantiate a class by using its name as a string. After some research, I discovered the following approach: const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype); This lin ...

The compatibility between JSON and the CORS header 'Access-Control-Allow-Origin' is crucial

I am trying to obtain the value from a JSON file that is located on the server. To retrieve this value, I am using AJAX. However, when checking the console for errors, I receive the following message: Cross-Origin Request Blocked: The Same Origin Poli ...

Strategies for extracting data from multiple Textareas in React

I am facing an issue with a form that contains multiple textarea elements (specifically 3). The problem is that when I type in one textarea, the content is automatically filled and updated in the other textareas as well. This behavior is not desired. I h ...

Retrieve data from specified <td> element in an ASP.NET MVC application

Within my View, I am displaying data using a table. Below is the code snippet: @foreach (var item in Model) { <tr > // Table row content here... </tr> } I have buttons with ...

Tips for speeding up the transition time of a floating header while scrolling

On this website , I am interested in adjusting the timing of the transition effect on the header background when hovering on scroll. Currently, the transition begins between two scrolls, but I would like it to start immediately after the first scroll. Can ...

Encountering TS7053 error while trying to access component variables using type indexing in Angular 13

When trying to access a variable with type indexing in Angular 13, I encountered a TS7053 error. However, in this Stackblitz example, the same code works without any errors. export class AppComponent { name = 'Angular ' + VERSION.major; Pro ...

How to troubleshoot Path Intellisense in VScode when using jsconfig.json for Next.js

In the structure of my project, it looks like this: jsconfig.json next.config.json components |_atoms |_Button.jsx |_Button.module.scss |_... |_... ... Within the jsconfig.json file, I have specified the following settings: { ...

How to incorporate a hyperlink into an Ajax-generated HTML table

I've successfully used thymeleaf in the past, but I'm having trouble implementing it with JavaScript and Ajax get requests. Essentially, I have a table that is generated dynamically. In my HTML script, an Ajax get request fetches and displays a ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...