61
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript undefined値の判定

Last updated at Posted at 2018-02-18

#javaSciprt undefined値の判定

javaScriptでは初期化していない変数にはundefinedがセットされている
※undefinedはプリミティブ値を示す

javascirpt
var tmp;
console.log(tmp); //->undefined

###当然文字列ではないので文字判定ではNG

javascirpt
var tmp;
if( tmp == "undefined"){
    console.log("true");
}else{
    console.log("false");
}
//->false

###typeof 演算子を利用する

javascirpt
var tmp;
if( typeof tmp === 'undefined'){
    console.log("true");
}else{
    console.log("false");
}
//->true

MDN参考

###厳格な等価評価

javascirpt
var tmp;
if( tmp === undefined){
    console.log("true");
}else{
    console.log("false");
}
//->true

undefined と厳格を行う事で評価することが出来るが、この方法は推奨されていない
MDN参考

###void 0と比較

javascirpt
var tmp;
if( tmp === void 0){
    console.log("true");
}else{
    console.log("false");
}
//->true

voidはあらゆる値に作用し、常にundefinedを返す演算子でそれを利用する
MDN参考

61
51
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
61
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?