Checking if a value exists
Dealing with non-existent values is a common need in JavaScript. Most often, you'll find yourself checking a property that may or may not be defined on an object you're currently working with. Other times, you might be working with an optional function argument, or with the return value of a function that returns a null in certain conditions. In all of these cases, you will likely want to do something with your value, but may need to treat it differently if the value is null, so as not to raise errors.
A common way to deal with this in JavaScript is:
if (myVar) { // Do something only if myVar is defined }
However, this is an oft-discussed source of bugs, since it will not run for other false-ish values, such as 0
, ""
, or false
. The preferred way to perform this check is safer, but clumsy:
if (typeof myVar != 'undefined') { // Do something only if myVar is defined }
Using the existential operator
CoffeeScript has a helpful existential operator to deal with these...