Operators

Other topics

Existential Operator

CoffeeScript's existential operator ? check if the variable is null or undefined.

1. Check for null or undefined.

alert "Hello CoffeeScript!" if myVar?

javascript equivalent:

if (typeof myVar !== "undefined" && myVar !== null) {
  alert("Hello CoffeeScript!");
}

2. Safer conditional assignment

You can also use this operator safer conditional assignment

language = favoriteLanguage ? "coffeescript"

javascript equivalent:

language = typeof favoriteLanguage !== "undefined" && favoriteLanguage !== null ? favoriteLanguage : "coffeescript";

3. Safe chaining of methods

Instead of chaining the methods with . chain them with ?. to avoid raising the TypeError.

firstName = user?.profile?.firstname

javascript equivalent:

firstName = typeof user !== "undefined" && user !== null ? (ref = user.profile) != null ? ref.firstname() : void 0 : void 0;

If all of the properties exist then you'll get the expected result if the chain is broken, undefined is returned

Full list of default operators

CoffeeScriptJavaScript
is, =====
isnt, !=!==
not!
and&&
or||
true, yes, ontrue
false, no, offfalse
@, thisthis
ofin
inNo equivalent
a ** bMath.pow(a, b)
a // bMath.floor(a / b)
a %% b(a % b + b) % b

Contributors

Topic Id: 4915

Example Ids: 17359,17868

This site is not affiliated with any of the contributors.