LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptでundefinedを判定する時の注意点

Last updated at Posted at 2019-03-10

JavaScriptでundefinedを比較する時の注意点です。

JavaScriptでundefinedを比較する時の注意点

typeofを使い、比較するのよりも直接===undefined比較するのが良いです。
下に例と解説を載せます。

console.log(typeof foo === "undefined"); // true
console.log(foo); // エラー
const foo = undefined;
console.log(foo); // undefined

このように、まだ宣言していない変数を評価するとエラーが発生してしまいます。
ですが、typeofで調べればこのエラーの心配はありません。
しかし、そのような場合はエラーだとはっきりわかった方が良いので、===を使って比較するべきです。

終わりに

私は現在、Web3のサービスの開発をしています。詳しくはこちらの記事をご覧下さい。
無料でイーサリアムが当たる、Web3時代の寄付サイトを作った話

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