Link to home
Start Free TrialLog in
Avatar of Andrew Downs
Andrew Downs

asked on

output only when greater than zero

I'm new to javascript, could someone tell me how to only print the output of the following expression if this.y > 0, thanks!
"(function(){return this.y + '('+this.percentage.toFixed(0)+'%'+')';})"
Avatar of Nitin Sontakke
Nitin Sontakke
Flag of India image

how to only print the output of the following expression if this.y > 0

I am not quite an expert in this area, however, you cannot choose either return a value or not return a value in a function. (Hope you get what I am trying to say here.....!)

So, technically, if this.y is 0 your function will still either return null or an empty string, depending on how we code it.

Now, assuming the caller simply displays whatever is returned, it fails. So basically suppress any display / output / log / etc to act if this.y == 0 then it should be handled before this function is called.

Have I made it complicated enough for you understand?
Avatar of Andrew Downs
Andrew Downs

ASKER

I have no idea honestly.  I just need to know the new expression to not output any values of zero
ASKER CERTIFIED SOLUTION
Avatar of Nitin Sontakke
Nitin Sontakke
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This doesn't output anything, it returns a value to a caller. If you meant to say how to return the empty string if y=0, then that's a direct if statement in the form (condition) ? ifvalue : elsevalue;

Anyway, why not make it more verbose, you're allowed to put more code before the return inside a function body, you can even let it span multiple lines, and add a comment:

function(){
var returnvalue= '';
// only show values >0:
if (this.y>0) ret = '('+this.percentage.toFixed(0)+'%'+')';
return returnvalue;
}

Open in new window


Bye, Olaf.
You mention > 0 but then what is expected data type of y? Is it float? What is expected min value of this.y?
correction:
function(){
var returnvalue= '';
// only show values >0:
if (this.y>0) returnvalue = '('+this.percentage.toFixed(0)+'%'+')';
return returnvalue;
}

Open in new window

@Olaf, am I right in stating that there is typo in your code? ret never used.

if (this.y > 0) returnvalue = '('+this.percentage.toFixed(0)+'%'+')';

Open in new window

Yes, I posted the correction.

...and I still forgot to put this.y in front.
Thank you so much!!!!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Both solutions work, Nitin was first. I contributed with an alternative and explaining the possible use of the ternary operator.