-2

I am printing out values of a values-array in a div. I have the following code which is working very well:

...
...
document.getElementById("div").innerHTML = "Value: " + values[i];

<div id="div">The Value will be displayed here.</div>

However some of the values in my values-array are negative, but I would like to only show positive numbers of the array. So if a number is negative, it should say 0 instead.

I tried the following but its not working:

...
...
document.getElementById("div").innerHTML = "Value: " + if (values[i] < 0) {0} else {values[i]};

Any clues or hints? I am new to javascript, help is appreciated.

maRtin
  • 6,336
  • 11
  • 43
  • 66
  • 2
    `"Value: " + (values[i] < 0 ? 0 : values[i]);` FYI - http://stackoverflow.com/questions/10270351/how-to-write-an-inline-if-statement-in-javascript – Cheery Nov 19 '14 at 23:00
  • That isn't how an `if/else` statement works in Javascript. – jfriend00 Nov 19 '14 at 23:00
  • try `document.getElementById("div").innerHTML = "Value: " + (values[i]<0)? 0:values[i];` – blurfus Nov 19 '14 at 23:01

3 Answers3

3

use ternary operator, as:

var vals = (values[i] < 0 ) ? 0 : values[i];
document.getElementById("div").innerHTML = "Value: " + vals;
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
3

Also consider Math.max:

document.getElementById("div").innerHTML = "Value: " + Math.max(0, values[i]);
Oriol
  • 274,082
  • 63
  • 437
  • 513
2

if statements do not 'return' a value; they indicate a code execution path, as in:

if this happens
   do this
else
  do that

you want to concatenate the a value depending on a condition, in your case, the ternary operator fits nicely as they return a possible value given a condition

var returnedValue = (condition)? value-if-true : value-if-false;

In your case:

var myValue = (values[i] < 0)? 0 : values[i]; document.getElementById("div").innerHTML = "Value: " + myValue;

Or putting it all together:

document.getElementById("div").innerHTML = "Value: " + (values[i] < 0)? 0 : values[i];

blurfus
  • 13,485
  • 8
  • 55
  • 61