LoginSignup
117
102

More than 5 years have passed since last update.

null と undefined の違い

Posted at

null は何かを返すべきですが、返すものがない場合。意図的に使われるものです。

undefined はただ何もない状態。定義されていない変数、オブジェクトの定義されていないプロパティ、何も return しない関数の返り値などは全て undefined です。

typeof の結果

console.log(typeof null);
// object

console.log(typeof undefined);
// undefined

undefined という変数を定義する

グローバルより内側のスコープでは undefined という変数を定義できてしまいます。null ではそういうことはありません。

var foo;
console.log(foo === undefined);
// true
console.log(foo == null);
// true

(function () {
  var undefined = 12;
  console.log(undefined);
  // 12
  console.log(foo === undefined);
  // false
  console.log(foo == null);
  // true
  console.log(typeof foo === 'undefined');
  // true
})();

それぞれの判別方法

undefined そのものかどうかを知りたい場合は typeof foo === 'undefined'

null そのものかどうかを知りたい場合は foo === null

どちらかかどうかを知りたい場合は foo == null ですかね。以下に示すように nullundefined 以外では false になります。

console.log(undefined == null);
// true
console.log(false == null);
// false
console.log(0 == null);
// false
console.log(NaN == null);
// false
117
102
2

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
117
102