LoginSignup
0
0

More than 3 years have passed since last update.

nullとundefinedの違いを忘れるので真剣に向き合ってみた

Last updated at Posted at 2019-12-01

nullとundefinedの違いって何??

null = 値が空
undefined = 未定義

オブジェクト作成して検証してみた!

const obj = {
  flag: true,
  sample: null // 値を初期化するときに使用する、値が空の意。
}

alert(obj.flag); // true
alert(obj.sample); // null
alert(obj.hoge); // undefined

obj.sample == undefined は 「true」 になる!

nullは、false
undefinedは、false

if(obj.sample == undefined) { // 等価演算子
  alert('true'); // true が出力される
}

obj.sample === undefinedは 「false」 になる!

厳密等価演算子を使用すると、obj.sampleの値は空だが、定義はされているのでfalseとなる。

if(obj.sample === undefined) { // 厳密等価演算子
  alert('true'); // true は出力されない
}
0
0
0

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
0
0