6
5

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.

undefinedの性質

Posted at

JavaScriptを使っていると、ほぼ確実にどこかで出くわすのがundefinedです。このundefinedですが、いろいろと扱いに面倒な点があります。

前提

文章をわかりやすくするため、undefinedな「値」については、「Undefined値」というように大文字にして「値」を付けて書きます。一方で、識別子としてのものはundefinedのように書きます。

Undefined値となるもの

以下のようなものが、Undefined値を持つ・あるいは返すものです。もちろん、意図的にUndefined値を代入することもできます。

  • 宣言だけで、何も代入されていない変数
  • 実引数が渡されなかった、関数の仮引数
  • void 式という形での、void演算子の実行結果
  • returnしなかった関数の返り値
  • 存在しないプロパティへアクセスした場合の結果

undefinedという変数

じつは、undefined変数です。ES3ではundefinedにUndefined値以外のものを代入できてしまったのですが、ES5ではグローバルなundefinedは上書き不可となっています。ただし、ES5でもローカル変数としてundefinedを宣言することはできてしまうので、依然として注意が必要です。

確実にUndefined値が必要な場合、自分で何もしない変数・仮引数を用意する、あるいはvoid演算子を使う、という方法があります。

Undefined値の特性

Undefined値は、以下のような特性を持っています。

undefined.js

//何も代入しなければUndefined値
var u;

//文字列に変換すると「undefined」
console.log('' + u);

//数値に変換すると、NaN
console.log(u - 0);

//プロパティを参照しようとするとエラーになる
console.log(u.some_property);

// null == undefined
console.log(u == null);

// typeofを取ると「undefined」
console.log(typeof u);

なお、存在しないプロパティを参照しようとするとエラーになるのは、nullとUndefined値だけに共通する性質です。

6
5
1

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?