Forum Moderators: open

Message Too Old, No Replies

return 0 if another variable is 0

         

ChrisVersion2

8:53 pm on Dec 8, 2008 (gmt 0)

10+ Year Member



Howdy Folks,

I'm trying to have var x equal zero if var y equals 0.

if var y is greater than 0 than war x will equal 240

This is the mess that I've coded. Novice level one I'm fully aware, any help or a direction would be great.

<script type="text/javascript">
var y = 15;
var x = wagemin;

wagemin()
{

if (wth <= 0)
{
return 0;
}
else
{
return 240;}
}
document.write(x)
</script>

daveVk

10:19 pm on Dec 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



TRY

<script type="text/javascript">
var y = 15;
var x = wagemin( y );
document.write(x);

function wagemin( wth )
{
if (wth <= 0)
{
return 0;
}
else
{
return 240;}
}
</script>

[edited by: daveVk at 10:21 pm (utc) on Dec. 8, 2008]

ChrisVersion2

1:10 pm on Dec 9, 2008 (gmt 0)

10+ Year Member



daveVk, thank you so much for you assistance

httpwebwitch

6:10 pm on Dec 9, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



allow me to introduce the ternary operator. it's an elegant way to write very simple true/false functions. it goes like this:

(condition) [b]?[/b] (return this if condition is true) [b]:[/b] (return this if condition is false)

thus your problem can be reduced to one simple expression, no function required:

x = (y>0) ? 240 : 0;

in pseudo-english pseudo-code, it's doing this:

assign to x the result of this operation:
is y greater than 0?
if true, return 240.
if false, return 0.

hence x will be 0 when y is 0 or less (including negative numbers).