0
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演算子:データ型を確認する

0
Posted at

定義と使い方

typeof演算子はオペランドのデータ型を文字列として返します。 この演算子は、変数や値のデータ型をチェックするために使用されます。

基本例

let a;
console.log(typeof a); // 出力: "undefined"

console.log(typeof true); // 出力: "boolean"
console.log(typeof 42); // 出力: "number"
console.log(typeof "Hello"); // 出力: "string"

この例は、typeof演算子が与えられた値のデータ型を示す文字列を返す方法を示しています。返される値は常に"undefined"、"boolean"、"number"、"string"など、JavaScriptであらかじめ定義された型名の文字列です。

構文

typeof operand // operandはオペランドを意味します

# operand

データ型を判別したい変数や値です。 より正確に言うと、返されるデータ型を確認したいオブジェクトやプリミティブ(primitive)データ値を表す式です。

この式はtypeof演算子の右側に位置し、typeof演算子はこの式を評価してその値のデータ型を判別し、結果を文字列として返します。operandは変数、定数、リテラル値、関数呼び出しなどが該当します。

let x = 42;
let y = "Hello";
let z = {key: "value"};

console.log(typeof x); // 出力: "number"
console.log(typeof y); // 出力: "string"
console.log(typeof z); // 出力: "object"

JavaScript:データ型と結果の例

/* Numbers */
typeof 24 === "number"
typeof 3.14 === "number"
typeof NaN === "number"

typeof parseInt("10px") === "number"
typeof Number("2") === "number"  
typeof Number("文字") === "number" 

/* Strings */
typeof "コーディング" === "string"
typeof "" === "string"
typeof `template literal` === "string"
typeof "24" === "string"
typeof String(24) === "string"

/* Booleans */
typeof true === "boolean"
typeof false === "boolean"
typeof Boolean(24) === "boolean"

typeof !!24 === "boolean" // 否定(!)を2回使うとBoolean()と同じです

/* Undefined */
var x;
typeof x === "undefined";
typeof undefined === "undefined";

typeof y === "undefined"; // 宣言されていない変数も"undefined"を返します

/* Objects */
typeof {param: 1} === "object";
typeof {} === "object";

typeof [1, 2, 3] === "object"; // 配列も"object"を返します
typeof [] === "object"; // 空配列も"object"を返します

typeof /regex/ === "object"; // 正規表現も"object"を返します

typeof null === "object"; // nullも"object"を返します

/* Functions */
function $() {}
typeof $ === "function";

typeof function () {} === "function";
typeof class ClassName {} === "function";

/* Symbols */
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";

/* BigInts */
typeof 1n === "bigint";
typeof BigInt("1") === "bigint";

活用例

実際の開発環境では、jQueryのような外部JavaScriptライブラリが正常にロードされているかを確認する必要がある場合がよくあります。 未定義のグローバル変数に直接アクセスすると通常はReferenceErrorが発生しますが、typeof演算子を使用すれば、エラーを出さずに安全に確認することができます。

以下の例は、jQueryライブラリがページにロードされているかを確認する方法を示しています。

if (typeof jQuery === "function") {
    console.log("jQueryがロードされて使用可能です。");
} else {
    console.log("jQueryはロードされていません。");
}

参考資料

codingEverybody:JavaScript typeof 演算子:データ型を確認する
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?