LoginSignup
0
0

More than 1 year has passed since last update.

React入門 - Tips9 - null,undefined,空文字

Posted at

目次

nullとundefinedと空文字の違いについて

こちらを参考にさせていただきました。
というか、こちらに全て書いてあります。

纏めます。

  • nullは、意図して変数にnullを代入して値がないことを示す。
  • undefinedは、 変数を定義(初期化していない)した状態 又は オブジェクトなどでキーが存在しない場合 (キー自体に?がついて必須項目で無い場合などに、キーが存在しないなど)
  • 空文字は、nullと似ているが、空文字が変数に入っている状態である。

null、undefined、空文字判定

以下試してみました。

const test1: string | null | undefined = '';
// const test2: string | null | undefined;  // これはtypescript的にエラー
const test3: string | null | undefined = undefined;
const test4: string | null | undefined = null;

console.log('test1-1:' +  (test1 === '' ? '=' : '' ))
console.log('test1-2:' +  (test1 === null ? '=' : '' ))
console.log('test1-3:' +  (test1 === undefined ? '=' : '' ))
if (test1) {
  console.log('test1-4:OK')
} else {
  console.log('test1-4:NG')
}

console.log('test3-1:' +  (test3 === '' ? '=' : '' ))
console.log('test3-2:' +  (test3 === null ? '=' : '' ))
console.log('test3-3:' +  (test3 === undefined ? '=' : '' ))
if (test3) {
  console.log('test3-4:OK')
} else {
  console.log('test3-4:NG')
}

console.log('test4-1:' +  (test3 === '' ? '=' : '' ))
console.log('test4-2:' +  (test3 === null ? '=' : '' ))
console.log('test4-3:' +  (test3 === undefined ? '=' : '' ))
if (test4) {
  console.log('test4-4:OK')
} else {
  console.log('test4-4:NG')
}

「null、undefined、空文字」を一度に判定したい場合、
つまり、値が入っていないことを確認したい場合、

if (変数名)

でいけますね。

==と===も違いがあるようですのでご注意を

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