-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.

3
  • 2
    "Value: " + (values[i] < 0 ? 0 : values[i]); FYI - stackoverflow.com/questions/10270351/… Commented Nov 19, 2014 at 23:00
  • That isn't how an if/else statement works in Javascript. Commented Nov 19, 2014 at 23:00
  • try document.getElementById("div").innerHTML = "Value: " + (values[i]<0)? 0:values[i]; Commented Nov 19, 2014 at 23:01

3 Answers 3

3

Also consider Math.max:

document.getElementById("div").innerHTML = "Value: " + Math.max(0, values[i]);
Sign up to request clarification or add additional context in comments.

Comments

3

use ternary operator, as:

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

Comments

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.