LoginSignup
35
23

More than 5 years have passed since last update.

変数が定義されているか、nullかどうかの判定をする[Javascript]

Last updated at Posted at 2018-11-29

変数が定義されているか判定する

ある変数が(ここでは hoge という名前とします)定義されていない状態で参照すると、

console.log(hoge) // ReferenceError: hoge is not defined

のように、「未定義ですよー」というエラーを発生させてしまいます。
それを回避するためには、

const hoge = 'fuga'
if (typeof hoge !== 'undefined') {
  console.log(hoge) // fuga
  console.log(typeof hoge) // string
  console.log(typeof undefinedVarible) // undefined
}

上記のように、typeof演算子というものを用いて判定します。
未定義のものに対してtypeof演算子を用いると、"undefined"という文字列が返ってくるのでそれで条件分岐ができます。

nullかどうか判定する

次に、ある変数がnullかどうか判定したいとしましょう。
先ほどのを真似して以下のように書くと...

const foo = null
if(typeof foo === 'null'){
  console.log('null')
}else{
  console.log('not null')
}

なんとこれ、else句に飛び込んできます。
こちらに書いてある通り、typeof null は "object" という文字列を返します。(歴史的な事情があるようです)

なのでnullの判定は素直に、

const foo = null
if(foo === null){
  console.log('null') // こっちが呼ばれる!
}else{
  console.log('not null')
}

と書いてあげましょう。

undefinedとnullをいっぺんに判定したいとき

undefined === null // false
undefined == null // true

と、イコール2つの比較をすると、undefinedとnullは等しいと判定されます。
それを利用して、 @forl_head_officer さんのコメントのように条件分岐することができます。

35
23
3

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
35
23