View Full Version : return with conditional operator

06-29-2006, 04:53 AM
I've been simplifying my scripts with conditionals and cutting down on if and else. I know you can use the conditional operator as follows when declaring a value of a variable:

Instead of:


Do this:


Can it also be used as a sort of inline function in the middle of a statement? Such as a return?

Instead of:

return 1
return 0

Can this be done?

return (true)?1:0

It worked in FireFox and IE, and I was told it was valid in C++ too. I just want to be sure that it isn't a bad coding practice that won't break across browsers. Is this a good idea or should it be avoided?

06-29-2006, 06:38 AM
Well a functions default is return true so you would really only need to specify false.

return false;

06-29-2006, 11:18 AM
If you need to return strictly the numbers 0 or 1, you may use the Number() method

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function returnNumber(Bool){
return Number(Bool)
<input type="button" value="TRUE" onclick="alert(returnNumber(true))">
<input type="button" value="FALSE" onclick="alert(returnNumber(false))">

06-29-2006, 04:44 PM
actually if you try this in your error console in firefox 1.5:

function x() {var q = 5;} alert(x());

The result is you alert undefined, not true as aero stated.

@Aero: where is what you said true? Is it perhaps not defined in the standard and therefore each browser can implement it differently. If so, it's completely unreliable for anything.

To answer the OP's question:

Ternary or inline conditions, in JavaScript, are evaluated like values, not like functions. It almost behaves like a function, but not quite. For example:


The statement above is a valid JavaScript token and it evaluates to the integer value 5.

q = 5;

The second statement above is a valid javascript token and it evaluates to the integer value of 5 as well.

(true ? 5 : 6)

This is a composite token, (it contains several tokens), and it also evaluates to the integer value of 5.

So you can use them as the right-hand side of statements like assignments, conditionals, and returns.

if (q == (something ? 5 : 6))
newValue = (color ? 'blue' : (shape ? 'square' : null));

return (newValue == null ? false : newValue);