简体   繁体   中英

Why ternary operator in JS with multiple statements is not working?

I know ternary operator with multiple statements works in React/JavaScript with:

condition ? (statement1,statement2,...) : (statement); .

Explored to get to know how it works.

Following is my code which is causing an error:

localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");

Error:

./src/reducers/reducer.js Line 26:21: Expected an assignment or function call and instead saw an expression no-unused-expressions

Search for the keywords to learn more about each error.

Similar code with if/else is working fine:

if (localProducts[productFoundAt].qty > 0) {
    localProducts[productFoundAt].qty--;
    localCartedProducts[iterator].qty++
} else {
    alert("More quantity not available");
}

What I am doing wrong here? Thanks for the help. Also why similar code working here?

 let a = 10; let b = 10; a==b ? (a-- , b--):alert("Hello World"); console.log(a); console.log(b);

That's a valid syntax. It is just an es-lint error which you can ignore by adding the following line:

/* eslint-disable no-unused-expressions */
localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");

Hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM