LoginSignup
1
2

More than 5 years have passed since last update.

未定義のundefinedと定義済みのundefined

Last updated at Posted at 2018-08-04

ことの発端はif文で二重否定(!!)で判定しているコードを見たときでした。
見慣れてなかったので調べてみるとどうやらundefinedやobjectをbool値に変換して判定しているらしい。
そもそも文字列の0やbool値が来たら値があるのに逆の判定されてしまうから個人的には嫌な書き方ですが。

とりあえずundefinedの二重否定時の動作を確認してみたところ

typeof test === 'undefined' ? console.log('true') : console.log('false');
console.log(!!test);
true
Uncaught ReferenceError: test is not defined
var test;
typeof test === 'undefined' ? console.log('true') : console.log('false');
console.log(!!test);
true
false

エラーが出てしまったので結局のところundefined判定(typeof test === 'undefined'など)は必要
そして、undefinedは未定義という意味だが未定義のundefinedと定義済みのundefinedがある?

未定義のundefined

test ? console.log('true') : console.log('false');
Uncaught ReferenceError: 'test' is not defined

定義済みのundefined

var test;
test ? console.log('true') : console.log('false');
false

おまけ

オブジェクト(未定義のプロパティはundefinedになる様子)

var test = {};
test.prop ? console.log('true') : console.log('false');
false
var test = [];
test[5] ? console.log('true') : console.log('false');
false
var test = {};
test.prop.prop ? console.log('true') : console.log('false');
Uncaught TypeError: Cannot read property 'prop' of undefined

undefinedはプリミティブ値なのでエラーになる 階層毎にundefined判定は必要
var test = [];
test[5][0] ? console.log('true') : console.log('false');
Uncaught TypeError: Cannot read property '0' of undefined

undefinedはプリミティブ値なのでエラーになる 階層毎にundefined判定は必要
1
2
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
1
2