Using Multiple Statements with the Ternary Operator in JavaScript

Is the way this JavaScript written valid? I came across an instance where someone included commas in the ternary operator conditions, and it was flagged as an error in my editor. The code didn't work on Chrome but ran fine on Firefox. After switching all the ternary statements to if/else statements, the application functioned correctly on Chrome.

a!==b ? (a=1, b=2) : (a=2, b=1)

Edit:

This is how the actual statement appears within the code:

a!==0?b<0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0

Answer №1

Absolutely, it's valid and functions smoothly in Chrome:

var x, y, z;

x = 6;
y = 7;
z = x !== y ? (x = 1, y = 2) : (x = 2, y = 1);
console.log("x = " + x);
console.log("y = " + y);
console.log("z = " + z);

I do acknowledge that the code may not be easily readable for humans. :-) It seems like a result of minification, as jamietre mentioned in the comments.

The comma operator is a binary operator that evaluates its operands sequentially from left to right, discarding the results of each operand except the last one. The conditional operator (ternary operator), on the other hand, selects one of two sub-expressions based on a condition.

In this case, there are a total of seven* different expressions nested within the ternary operation, resulting in either a value of 2 or 1 based on the initial comparison between x and y, along with assigning values to x and y.

Using the comma operator for side effects can make the code less maintainable. It's crucial to consider whether using the comma operator adds any substantial benefits when the left-hand operand doesn't have significant side effects.


* Yes, seven separate expressions within the overall ternary operation:

  • x !== y
  • the first comma expression
  • x = 1
  • y = 2
  • the second comma expression
  • x = 2
  • y = 1

Regarding your edit containing the updated statement, that also works effectively:

function evaluate(num) {
    var b = 7,
        d = 1,
        e = 2,
        f = 3,
        g = 4,
        h = 5,
        i = 6;
    
    num !== 0 ? b < 0 ? (h = b / num, e = h - 1, f = -2 * b + 2 * num * e, i = -2 * b + 2 * num * h, d = 2 * h * num - 2 * b - 2 * num) : (h = b / num, e = h + 1, f = 2 * b - 2 * num * e, i = -2 * b + 2 * num * h, d = -2 * h * num + 2 * b) : d = h = e = f = i = 0;
    
    console.log("num = " + num);
    console.log("b = " + b);
    console.log("d = " + d);
    console.log("e = " + e);
    console.log("f = " + f);
    console.log("g = " + g);
    console.log("h = " + h);
    console.log("i = " + i);
}

evaluate(0);
evaluate(1);
.as-console-wrapper {
  max-height: 100% !important;
}

However, I sincerely hope this code is minified because if someone wrote it in this form, they must have a strong aversion towards future maintenance efforts... ;-)

Answer №2

Affirmative:

x=1;
y=2;

x!==y ? (x=1, y=2) : (x=2, y=1)

console.log(x);     // 1
console.log(y);     // 2

also:

x=1;
y=2;

x===y ? (x=1, y=2) : (x=2, y=1)

console.log(x);     // 2
console.log(y);     // 1

By considering the comparative operator adjustments, it is evident that they deliver accurate outcomes in our analysis.

Answer №3

Alternatively, you could try:

b = a !== b ? (a=1, 2) : (a=2, 1);

For more information on the comma operator, check out this resource.

The comma operator evaluates each operand in sequence (from left to right) and returns the value of the last operation.

Answer №4

Exploring this topic further using ES6 code examples. When utilizing one side of the TRUE : FALSE argument to loop through all scenarios within an IF statement, it may be beneficial to organize the code in a manner similar to a switch | case structure.

While nesting implies the presence of branching logic, unnecessarily complicating the process by writing nested IF statements can make the code more convoluted. It's like being overly verbose when presenting a problem to a jury. In my opinion, it is better to simplify the explanation as much as possible. The example provided demonstrates a logical approach to expressing nested IF conditions where the TRUE condition is executed. The final ELSE block serves as a fallback for when none of the previous conditions are met. choreDoor can have values of 0, 1, or 2:

choreDoor === 0 ? 
   (openDoor1 = botDoorPath,
    openDoor2 = beachDoorPath,
    openDoor3 = spaceDoorPath)
: choreDoor === 1 ? 
   (openDoor2 = botDoorPath,
    openDoor1 = beachDoorPath, 
    openDoor3 = spaceDoorPath) 
: choreDoor === 2 ?
   (openDoor3 = botDoorPath,
    openDoor1 = beachDoorPath, 
    openDoor2 = spaceDoorPath)
: false;

Answer №5

For those who prefer to avoid utilizing the Comma operator (,), an alternative approach involves using nested Conditional (ternary) operators.

var x = 6;
var y = 7;
var z = (x !== y)?  // true
        ((x = 1 || 1===1)? (y = 2) : null) // will first execute x=1, then y=2
      : ((x = 0 || 1===1)? (y = 0) : null);

console.log("x = " + x);
console.log("y = " + y);
console.log("z = " + z);

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

Incorporating AJAX functionality into an existing PHP form

I am currently working on a PHP registration form that validates user inputs using $_POST[] requests. Validating username length (3-20 characters) Checking username availability Ensuring the username matches /^[A-Za-z0-9_]+$/ pattern and more... Instead ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Having difficulty retrieving the specific Laravel validation error message through AJAX

In my Laravel project, the error message I am encountering is: {message: "The given data was invalid.", errors: {oData: ["validation.required"]}} errors: {oData: ["validation.required"]} message: "The given data was invalid." I am not trying to display ...

CSS and JavaScript issues causing compatibility errors with Internet Explorer

Recently, I've been working on a portfolio website just for fun, and I'm encountering compatibility issues specifically in Internet Explorer. Surprising, right? The issue seems to be stemming from the flipcard.css and flipcard.js files. While oth ...

There seems to be a mysterious issue with the addClass function in jQuery, as it is not behaving

I am facing an issue with the function showColorStart() as it is not working as expected. When this function is called, the background color of the squares should change to the color specified in the array colorspicked[lindex], but it is not doing so. I ha ...

Error in Drag and Drop functionality in Dojo 1.6 (Source.xd.js line 8)

http://jsfiddle.net/ykNJ8/ While working on a vanilla implementation from the CDN on localhost, I encountered an issue I can't seem to replicate consistently. It mainly happens when dragging items near the bottom of the list. The dragging tool-tip is ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

Clicking the Javascript styling toggle does not function properly on the initial click

I'm currently developing an HTML application with a sidebar menu that toggles on click. However, I've encountered an issue where the menu doesn't appear until the second click. The first click seems to have no effect. Here's the CSS co ...

What causes my TypeScript to occasionally return an instance and other times return a class?

I've been developing an app to enhance my understanding of TypeScript. It functions perfectly in Chrome, however, I encounter a problem when running it in Edge. The issue lies within this method: set position(pos: Point) { const diffAsPoint ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

The React Bootstrap button appears to have a washed-out appearance

I utilized the following code snippet: <Button bsStyle="primary" bsSize="large">Primary</Button> My approach differs from a similar question discussed at React-bootstrap button bsStyle as I have integrated the bootstrap css directly into the ...

Encountering a data property error while trying to render ejs using axios

I am encountering an error message "TypeError: Cannot read property 'data' of undefined" when trying to display results.ejs using data from an API. Can someone help me identify what's incorrect with the rendering code? Thank you. index.js: ...

Is there a way to convert my validation function into an AJAX method?

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); f ...

How can WebRTC be used to minimize latency between devices transmitting video streams?

Apologies for not including any code, but I am currently focused on expanding my knowledge of latency and webRTC. What methods are most effective in minimizing the latency between multiple devices sharing a video stream? Alternatively, how can we reduce l ...

Guide on transforming a text element into an input field when clicked using AngularJS

I'm curious about how to achieve this functionality using AngularJS. Specifically, I'd like to display a list of keywords with an edit button next to each one. <tr ng-repeat="keyword in keywords"> <td> <st ...

Is there a way to efficiently select and transfer multiple data in the specified format using Vue.js in HTML?

I am struggling with passing the data as per the specified format. rules : [{ name:null, section:null, data : [{head:null,value:null}] }], The challenge I am facing revolves around passing data in this particular format. I h ...

Performing actions after using the .html() method

I'm encountering an issue with this particular piece of code: if(s.length > 0){ jQuery("#ajax-load").html('<img src="/wp-content/themes/fearlessly/images/712.GIF" style="margin: 208px auto; width: 50px; height: 50px; display:block;" /& ...

Launch a modal component upon submitting an Axios post request

Is it possible to implement a timeout in an open modal when a user creates an account using the onSubmit function with axios post for user registration? I have the modal component created with redux, but I'm not sure how to integrate it into this Axi ...

Is it possible to perform arithmetic operations on several specific elements within an array without having to use a loop?

Currently, my goal is to add two numbers from an array using the code below. However, instead of adding them together, it seems that the code is only concatenating them. if (this.id == "=") { if (HYUTS[1] == '+') { var sum = ...

Is there a programming language that generates JavaScript code?

I am in search of a language that operates at a higher level than JavaScript, akin to how C++ relates to assembly code. The ideal higher-level language would offer type-safety, easy refactoring, support for classes, inheritance, and other features similar ...