In CoffeeScript, what is the simplest way to check if a key exists in an object?
Asked
Active
Viewed 6.1k times
3 Answers
186
key of obj
This compiles to JavaScript's key in obj
. (CoffeeScript uses of
when referring to keys, and in
when referring to array values: val in arr
will test whether val
is in arr
.)
thejh's answer is correct if you want to ignore the object's prototype. Jimmy's answer is correct if you want to ignore keys with a null
or undefined
value.

Trevor Burnham
- 76,828
- 33
- 160
- 196
-
2most likely `own key of obj` works, too, to aditionally test `.hasOwnProperty()`. the “most likely” comes from me not having tried, but this syntax working in comprehensions. – flying sheep Jan 13 '13 at 21:15
-
2@flyingsheep No, it only works in comprehensions. Try it: http://coffeescript.org/#try:own%20key%20of%20obj – Trevor Burnham Jan 13 '13 at 22:24
-
ah, [ok](https://github.com/jashkenas/coffee-script/issues/1019): `own = (prop, obj) -> Object::hasOwnProperty.call obj, prop` – flying sheep Jan 14 '13 at 13:33
38
The '?' operator checks for existence:
if obj?
# object is not undefined or null
if obj.key?
# obj.key is not undefined or null
# call function if it exists
obj.funcKey?()
# chain existence checks, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?.grandChildKey
# chain existence checks with function, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?().grandChildKey

limscoder
- 3,037
- 2
- 23
- 37
-
17
-
In the case where one doesn't care about the key existing but being null, then `obj.key?` is probably the most concise. – Andrew Mao Jun 27 '14 at 14:38
22
obj.hasOwnProperty(name)
(to ignore inherited properties)

thejh
- 44,854
- 16
- 96
- 107
-
I like this response because `key of obj` will throw an error if the value is a string or number. `Cannot use 'in' operator to search`. In this case if the object is not undefined and not null it will work. – jqualls Jun 25 '14 at 20:14
-