View Full Version : Difference between return 0 and return false

01-07-2004, 12:23 AM
On a page, I had <body onhelp="window.location='../help.htm';return false">

It worked fine. But why is it that when I put return 0 it doesn't hide the help menu? the boolean integers have always worked for me in functions, why don't they work now?

01-07-2004, 01:01 AM
Because zero and false have different purposes, as they are different things. In a condition statement (using == ), zero and false are treated as the same thing. But if you use ===, zero and false are not treated as the same. Sometimes you need to find zero without being false.

Using return 0, will return zero, which is a number. Using return false says that there is nothing to return, or don't return.

01-07-2004, 01:04 AM
I've used functions like this all the time, and it works for true and 1. And even using 0 or false (or the !not operator) works with it.

function c(X)
if(document.forms[0][X].checked){return 1}

I've never encountered a triple === before. I think it's a PHP thing, but what's the logic of it? Does it apply to javascript?

01-07-2004, 03:14 AM
In condition statements, true/1 or false/0 is treated as the same, but in event handlers, you need to return a real boolean true/false (not 1/0) to (usually) suppress the event or not.

<a href="page.htm" onclick="return false">Unclickable link</a>
<body oncontextmenu="alert('No context menu');return false">

You can do a return 1/0 in a function if the output of that function will be used as a conditional statement.

function c(X)
if(document.forms[0][X].checked) return 1;
else return 0;

if (c(0)) // 1/0 is typecasted as true/false internally
alert("The first element is checked.");
alert("The first element is not checked.");

I don't know if I explained it well. But I hope that clears things up a bit.

01-07-2004, 03:19 AM
Makes perfect sense to me. Functions I make can accept 1 and 0, but internal functions or events require the real true/false deal.

01-07-2004, 04:10 AM
=== means strict equality:

("3" == 3) // true
("3" === 3) // false

01-07-2004, 12:10 PM
in statements like 0:1 the real meaning is yes/no, which are not strictly boolean operators. There is a difference between comparation ( 0:1 ) in an if statement) and existence (true/false) in a return function. Existence is a strictly boolean affair, while comparation can be a classical math one...

01-07-2004, 12:22 PM
This is really a hack made by Netscape to ease the creation of event handlers (that is internally, not from your POV). You see, a function does return undefined by default, if there is no return statement to say otherwise. But, undefined autocasts to false and they wanted to make returning false cancel the event. So, they made an internal strict comparison instead of a regular one, which gives the effect that only a boolean false actually cancels the event, as there is no autocasting taking place.