Question

I am fetching some big json data from back-end and and I have to check the data twice and only then I can use that data. In nested if my code is working properly I want to change that in to nested ternary condition. following is my code (Fiddle)

JS:

var x = /* Some big JSON data */,fx,yy;
if(x){
    yy = $.parseJSON(decodeURIComponent(x));
    yy ? fx = yy.products.length : fx =0;
}else{
    fx = yy = 0;
}

This is what I have tried yet(not working):

x ? ($.parseJSON(decodeURIComponent(x)),(yy ? fx = yy.products.length : fx =0;)) : (fx = yy = 0);

this is Fiddle

Was it helpful?

Solution

Frankly, it would be much better to write this as

var x = /* whatever */, fx = 0, yy = 0;

if (x && yy = $.parseJSON(decodeURIComponent(x))) {
    fx = yy.products.length;
}

which is immediately clear to the reader.

Another way to write it with idiomatic Javascript (still no ternary operator) would be

var x = /* whatever */, yy, fx;
yy = $.parseJSON(decodeURIComponent(x)) || 0;
fx = (yy && yy.products.length) || 0;

which you can also write in one line by combining the declarations of yy and fx with the assignments. That's one statement less than the ternary operator, so if you are "optimizing" for statement count why not do that instead?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top