-1

I am trying this code

<script>
    var x=1;
    var temp = '{"value":'+ (x==1)?1:0 +'}';
    console.log(temp);
</script>

and expecting to give output like this {"value":1} but it is consoling only 1 why not the whole obj. string can anyone tell me that what's wrong ?

3 Answers3

1

Beside the missing parenthesis

var temp = '{"value":'+ (x == 1 ? 1 : 0) +'}';
//                      ^^^^^^^^^^^^^^^^

to give the conditional (ternary) operator ?: a higher operator precedence over the plus sign, you could use a different approach by using a short hand property for an object with ES6.

Thi sgenerates an object, instead of a string, which is better to generate. For using a stringified value, JSON.stringify creates a string in the wanted format.

var x = 1,
    value = x === 1 ? 1 : 0,
    temp = { value };

console.log(JSON.stringify(temp));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Your ternary statement is immediately followed by another + which it doesn't understand how to read. It appears incomplete as "0 + " [...nothing].

To evaluate that statement separately for use in the concatenated string, you need to either evaluate it in another statement, or enclose it in parentheses.

var x=1;
var temp = '{"value":'+ (x == 1 ? 1:0) +'}';
console.log(temp)

Or, you could use ES6 Template Literal string interpolation instead of using + signs to concatenate the separate parts ... This syntax evaluates your ternary expression inline, then places the result inside the variable placeholder indicated by the dollar sign & curly braces ${[variable]}. The resulting string prints the value of the interpreted expression.

var temp = `{"value":${(x == 1) ? 1:0}}`
mc01
  • 3,750
  • 19
  • 24
0

Change your expression like below

var temp = '{"value":'+ (x==1?1:0) +'}';

Gnana
  • 144
  • 7