I often want to check if a variable or property is not null and not undefined in CS. Is there a shortcut for "truthy"-checks besides the postfix ?
for undefined
?
Asked
Active
Viewed 129 times
1

Julik
- 7,676
- 2
- 34
- 48
-
3According to http://stackoverflow.com/questions/9929306/coffeescript-undefined, `?` checks both. – Austin Mullins Mar 20 '13 at 22:41
-
1Thanks! closing as a dupe – Julik Mar 20 '13 at 23:56
1 Answers
1
@Austin Mullins, Thats true but I assumed it produced that check for everything and found that the CoffeeScript compiler will produce different results based on the use of the variables.
Variables that are declared before use (assigned a value) check for != null. Even explicit assignment of undefined (the Javascript compiles to void 0 which returns undefined) won't change the compilers behaviour.
The result is the same regardless ? appears work as expected.
A demo of what I found (preview link), http://preview.tinyurl.com/cmo6xw7
Follow the link and click the Run button (top right)
The code...
((arg) ->
str = "Hello World!"
num = 42
foo = arg
# Lets see what the compiler produces
alert "str is #{str}" if str?
alert "num is #{num}" if num?
alert "foo is #{foo}" if foo?
# bar has not been assigned a value or used until now
alert "bar is #{bar}" if bar?
# Lets assign str to something that isn't straight up null
# cs will translate undefined into the expression that returns undefined
str = undefined
# Shorthand
if str?
alert "str? is #{str}"
else
alert "str? is empty"
# Explicit checks
if typeof str isnt "undefined" && str isnt null
alert "str explicit check is #{str}"
else
alert "str explicit check is empty"
).call()

Shane Maiolo
- 171
- 4
-
2It works because `!=` and `==` coerces it's operands. `undefined == null // true` and `undefined != null // false`. But `false != null // true`. Which means, `a != null` would be true for `null` or `undefined`, but a literal false would return `true`. And it's different for an undeclared variable because referencing an undeclared variable would raise a runtime exception if you don't handle it carefully with `typeof` first. – Alex Wayne Mar 21 '13 at 00:26