0

Similar to this topic: CoffeeScript Existential Operator and this

The coffeescript, I'm having a problem using the elvis operator:

foo = -> 
  y = foo()
  console.log 'y is null' unless y?
  console.log 'x is null' unless x?

Compiles to:

var foo, y;
foo = function() {};
y = foo();
if (y == null) {
  console.log('y is null');
}
if (typeof x === "undefined" || x === null) {
  console.log('x is null');
}

Output:

y is null
x is null

So the problem is that since y is assigned earlier that coffee takes the shortcut and assumes that y cannot be undefined. However, it is valid to return undefined from a function.

Is there a "safer" way to check that y is also not undefined?

UPDATED Clarified Examples and Explanation:

From the comments, in the first if statement (y == null) is using double equal instead of ( x === null) triple equal, as in the second if statement. Clever.

Community
  • 1
  • 1
bryce
  • 763
  • 6
  • 13
  • i think you're conflating three different things here: (1) does `y` exist / has it been declared? (2) does `y` have the value `undefined`? (3) does `y` have the value `null`? – flow Oct 10 '13 at 14:06

1 Answers1

3

? operator always checks if the value is neither null nor undefined.

y == null is absolutely correct way to check that the value of y is either null or undefined in JavaScript.

For example, the following CofeeScript code checks only for null values:

do_something() if y is null

which compiles to

if (y === null) do_something();

So, while y? (y == null in JS) checks for both null and undefined, y isnt null (y !== null in JS) checks only for null.

Check this answer for more detailed information.

See this answer for more info about equality checks in JavaScript.

Community
  • 1
  • 1
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
  • "? operator always checks if the value is neither null nor undefined." Thats what I thought, but in my example above it doesn't check for undefined only null. So y gets assigned to undefined, then fails the check against null. – bryce Oct 10 '13 at 14:12
  • 2
    @bryce look closely to your example, it checks for `y == null` which is actually `null` or `undefined`. Real `null` check is `y === null` and not `y == null`, see my example above. – Leonid Beschastny Oct 10 '13 at 14:46
  • @bryce See [this answer](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) for more info about equality checks in JavaScript. – Leonid Beschastny Oct 10 '13 at 14:48