LoginSignup
14
13

More than 5 years have passed since last update.

CoffeeScript で null かどうかを判断するイディオム

Last updated at Posted at 2013-01-22

訂正その二

JavaScript
if (json['hoge'] == null) {
  console.log('hoge は null です');
}

を CoffeeScript で書くと

CoffeeScript
unless json['hoge']?
  console.log 'hoge は null です'

or

# JavaScript として評価する
if `json['hoge'] == null`
  console.log 'hoge は null です'

と書けます。

記事の内容が不適切でしたので、訂正してお詫びします!


訂正

コメントで頂きました。

CoffeeScript
unless hoge?
  console.log 'hoge は null です'

が一番スマート。


オリジナル

CoffeeScript で

CoffeeScript
if hoge is null
  console.log 'hoge は null です'

とすると、コンパイル後のコードは

JavaScript
if (hoge === null) {
  console.log('hoge は null です');
}

になってしまい、null の比較が失敗してしまう。

そんなときは、

CoffeeScript
if `hoge == null`
  console.log 'hoge は null です'

のように、JavaScript として評価されるようにすると

JavaScript
if (hoge == null) {
  console.log('hoge は null です');
}

になって、幸せになる。

※ Underscore の _.isNull をつかうでもいい

14
13
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13