Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times:

this.className != 'selected' ? this.className = 'selected' : this.className = 'unselected';

Eventually, I figured out a workaround..

this.className = (this.className != 'selected') ? 'unselected' : 'selected';

..but I'm curious if there's a way to achieve the same outcome with this.className being mentioned only once, like this:

this.className = 'selected' ? 'unselected' : 'selected';

Any suggestions would be appreciated.

Answer №1

...my inquiry is centered around the possibility of achieving the same functionality with only one instance of this.className being written, similar to this concept.

Unfortunately, that is not feasible. In most cases, your second option is the closest solution:

this.className = (this.className != 'selected') ? 'unselected' : 'selected';

If you were to go with your third option, it would constantly set the value as 'unselected' since 'selected' evaluates as truthy, causing the second operand ('unselected') to always be chosen.


Delving into the specifics regarding DOM elements and classes: You could simply use a single `selected` class and toggle it accordingly (perhaps through

this.classList.toggle('selected')
). Not having the class would essentially equate to having the `unselected` class present.

Answer №2

Opting for the second choice is highly recommended

this.className = (this.className != 'chosen') ? 'unchosen' : 'chosen';

The third option is clearly incorrect!

Answer №3

When faced with this task frequently, it may be beneficial to create a method to handle it

function toggleProperty(obj, prop, value1, value2){
  obj[prop] = obj[prop] === value1 ? value2 : value1;
}

var myObject = {
   attribute:"value"
}

console.log(myObject.attribute);
toggleProperty(myObject,'attribute', 'value', 'new value');
console.log(myObject.attribute);
toggleProperty(myObject,'attribute', 'value', 'new value');
console.log(myObject.attribute);

Implementation example:

 toggleProperty(this,'className','active','inactive');

Answer №4

In my opinion, state and class names should be considered as separate entities.

One approach could be to use a variable to store the state, for example:

this.isChecked = !this.isChecked;
this.className = (this.isChecked ? 'un' : '') + 'checked';

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

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Retrieve a JSON WebMap using an ArcGIS JavaScript API Map object

Is there a way to retrieve a JSON representation of a WebMap object from a JavaScript Map object in the ArcGIS JavaScript API without relying on ArcGIS.com? It would be ideal if there was a method similar to: webMapAsJSON = map.toWebMap(); The "Export We ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

What is the best way to send the totalAmount data from one child component to its parent, and then pass it on to another

I am facing an issue with passing the totalAmount data from cart.js to the parent component (app.js) and then further to another child component (info.js). Despite my attempts, it seems like I am unable to pass it correctly as I encounter the following err ...

Is there a way to receive a JSON request in Express delete using Restangular?

Below is the Restangular code that I am using for deleting an object: $scope.delO = (id){ Restangular .one("footer", id) .get() .then((ob) => { ob.remove(); } .catch.... } The deletion request is being successfully sent, co ...

Is it possible to use jQuery validate for remote parsing with two fields in a single call

Currently, I am facing an issue while trying to parse two values using jQuery's validate plugin to compare with an SQL database. The DateReceived value is successfully parsed, but the CentreID value always appears as null. Below is the code snippet I ...

The JSX function seems to be malfunctioning, as the function part is not displaying on the webpage as intended

This code snippet is a part of a React component in a project. I have imported a CSS file for styling and have already integrated Material UI. However, the function for the new article is not displaying on the webpage as expected. import "./Widgets. ...

Accessing Session Objects in Struts2 Using a Different Session Object as a Key

I am fairly new to working with Struts2 and currently, I am faced with the challenge of retrieving a session object using a dynamic session key. Here's how my application flow goes: The user will trigger the action from their browser http://localhos ...

Obtain the unique identifiers for each element within an array and attach them to the option values for each item

Forgive me for any misuse of terms, as I am relatively new to Javascript. However, I hope I can describe the desired result effectively in order to receive assistance with my inquiry. Within the code snippet below, there is an array named dates that outpu ...

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Unable to integrate bootstrap with webpack

Incorporating Express, Webpack, and Bootstrap. Currently utilizing css-loader for my stylesheets. Below is the contents of my webpack.config.js: const path = require("path"); config = { "entry": "./modules/entry.js", "output": { "path": p ...

What is the process for comprehending an event that is not triggered by the task queue within the event loop specifications?

According to the guidelines: Various events are triggered through tasks apart from just the task queue. I am curious to understand what exactly is meant by "various" and the specific types of tasks being referred to here? ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Identifying HTTP Live Streaming on mobile devices

I am seeking a reliable method to determine if a mobile device can play HTTP Live Streaming (m3u8). Currently, I am using the following script for testing purposes: function isHLSEnabled() { var videoElement = document.createElement('video' ...

transforming JSON information into tables on a webpage

Can someone help me with the challenge of incorporating a massive JSON file into an HTML table? I am encountering an issue where I continuously receive the error message Uncaught TypeError: v.forEach is not a function. Any guidance would be greatly appreci ...

Fixed width for the last column in DataTables

Here's the scenario: I have a jQuery script that loads DataTables, and I know how to set the "aoColumns" : "sWidth" parameter to fix the width of a specific column, which is working fine. However, my issue arises from having multiple tables with var ...

The index "is_ajax" has not been defined

I attempted to create a simple login functionality using Ajax. Following a tutorial that didn't use classes and functions in PHP, I tried restructuring the code with classes and functions. However, I encountered the error: Undefined index: is_ajax He ...

Having trouble removing items from the data grid list in react material-ui, any thoughts on what might be causing the issue?

I'm facing an issue with deleting items from a basic list of customers rendered using material UI DataGrid. Even though I can retrieve the specific customer id when logging to the console, I am unable to delete the item from the list. You can view my ...

Uploading a three.js canvas to the server without saving it as a file

Currently, I am in the process of saving an image to the server using a three.js script that I have created. The script looks like the following: actualCode(THREE); function actualCode(THREE) { //Rendering variables const renderer = new THREE.WebG ...

What is the best way to identify when a page has been refreshed in Reactjs?

Imagine a set of pages with steps: 1, 2, and 3. If a page reloads during the second or third step, it must be directed back to the first step. Is there a way to identify when a page has been reloaded? ...