1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】typeof === "number"で数値判定する時の注意点

1
Last updated at Posted at 2026-01-09

はじめに

数値判定のロジックとしてtypeof === "number"を使っている記事をよく見かけるのですが、想定外の動作が無いか気になり調査しました。

注意点

NaNも"number" としてtrue判定される

typeof NaN === "number" // true

NaN(Not a Number)は計算結果がおかしい場合に返される値。次の計算をした時に答えが数値にならない場合はNaNが返る。

  • 0/0
  • "Hello" - 1
  • parseInt("Hello")

NaNをはじきたい場合は、typeof NaN === "number"で判定する前に、Number.isNaN()を使い判定すればOK

const val = 0/0;
if (Number.isNaN(val)) return;

if (typeof val === "number") {
  console.log(これは数字);
}

整数か浮動小数点数かまでは判定できない

typeof 1 === "number"   // true
typeof 1.5 === "number" // true

整数か知りたい時はNumber.isInteger()を使う。

BigInt(かなり大きい数字またはかなり小さい数字)はfalseと判定

typeof 123n === "number" // false

BigIntの判定はbigintプリミティブを使う

typeof 123n === "bigint" // true

BigIntはECMAScript 2020以降で使えます

まとめ

typeof === "number"の判定まとめ

備考 判定
123 整数 true
123.0 小数 true
0xff 16進数 true
0.255e3 10進指数 true
"Hello" 文字列 false
"999" 数字を文字列表示 false
NaN - true
undefined - false
null - false
true - false

おわりに

他の記事で書かれていることでも環境が変われば想定外の動作(落とし穴)になるので、簡単そうに見えることでもしっかり調べるようにしよう。

参考

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼
https://projisou.jp

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?