A quick post in the continuing series on programming in JavaScript from a C# developer's perspective.
In this episode, we're going to look at truth within boolean and conditional expressions.
In C#, you know that when you're constructing some conditional expression for your if
statement the expression must evaluate to either true or false. The expression is either a boolean variable or function returning a boolean, or is some kind of comparative expression using other types. You learn pretty quickly to use ==
instead of =
because the compiler warns you, and so on. There are no short-cuts like the bad old days of C, where things like integers would be evaluated as either true or false, depending on whether they were non-zero or zero.
Well, welcome back to those days. JavaScript has a whole bunch of simple rules about what's evaluated as "true", or "false". The easiest way to learn this is to look at the values that are evaluated when necessary as false
:
false
(of course!), a booleannull
, which is of type null
undefined
, which is of type undefined
0
NaN
(this is just ... weird)''
Everything else evaluates as true
.
Let's see what this means in practice. Suppose you need to know if a variable is set to a value.
if (someVariable) { // someVariable exists and is usable }
The condition here is doing double duty. If the variable is undefined
, the condition evaluates as false
. If the variable exists, but is null
, the condition again evaluates as false
. It's only if the variable has been declared and initialized to a non-null value that the if
block would be entered.
Remember the String.IsNullOrEmpty()
method in C# where you're testing for a string to be either null
or be the empty string?
if (string.IsNullOrEmpty(someString)) { someString = "missing"; }
In JavaScript, you would get rid of the visual noise of the method call. (Also see below for an extra note.)
if (!someString) { someString = "missing"; }
Suppose you need to know if a variable has a property called Foo
. If it doesn't, you want to create one and set it to 42.
if (someVariable && !someVariable.Foo) { someVariable.Foo = 42; }
In other words, "if SomeVariable
exists and is non-null and someVariable.Foo
doesn't exist".
Note that the usual &&
, ||
, and !
operators are all present. Similarly you must put your conditional expressions in parentheses, like in C#.
In C#, to test whether two values are the same as each other you'd use the ==
operator. (OK, you could also call some method to do the comparison, for example, if the two values were strings.) JavaScript also has the ==
operator, but in general you shouldn't use it. A better equality comparison operator is the ===
operator (triple-equals), known as the identity operator. Why?
The problem with the double-equals operator is that the interpreter will make great efforts to coerce the two values being compared into the same type so that they can then be compared. It's a "lazy" comparison, not for the interpreter, but for the programmer. The triple-equals operator is much more rigorous — it checks the type to be equal too.
Let's see some examples. If you run this set of statements in Firebug within Firefox, they'll all print true
:
console.log(null == undefined) console.log("42" == 42) console.log('' == 0) console.log('0' == 0)
The rules for why these all evaluate as true are simple enough, but my recommendation is don't rely on ==
. For example, check out the last two statements. Since the empty string equals 0 and 0 equals the string '0'
, then it must imply that '' == '0'
. Sorry, nice try, but no it doesn't. Since ==
can produce examples where the operator is not transitive, against all common logic, that's a reason not to use it in my book. Stick to ===
and !==
, that's my advice.
Above I gave some examples of using the various values that evaluate to false
. They can, in fact, be drastically shortened using some special JavaScript syntax. Here's the string example, rewritten:
someString = someString || "missing";
The ||
(or) operator here has a special meaning. It produces the value of the first operand if the first operand evaluates as true
, otherwise it produces the second operand. Think about that for a moment. It evaluates the first operand as a boolean expression, and if that expression is true
, it returns the operand itself. If it evaluates to false
, then the second operand is returned.
The &&
operator has a similar special meaning. It produces the value of the first operand if the first operand evaluates as false
, otherwise it produces the second operand. Any example would be too weird to someone with a C# hat on, but in essence the following two expressions are equivalent:
if (count === 100) { startNewPage(); } (count === 100) && startNewPage();
It's ugly, and I don't recommend using it; however, it's likely you'll see it in code. The ||
operator on the other hand will produce some fairly readable code.
Now playing:
Yello - Lost Again
(from Hands on Yello)
1 Response
#1 Dew Drop – February 16, 2009 | Alvin Ashcraft's Morning Dew said...
16-Feb-09 7:18 AMPingback from Dew Drop – February 16, 2009 | Alvin Ashcraft's Morning Dew
Leave a response
Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.
_emphasis_
**strong**
[text](url)
`IEnumerable`
* an item
1. an item
> Now is the time...
Preview of response