JavaScriptにおけるデータ型
この記事ではJavaScriptにおけるデータ型について説明します。
YouTube Video
JavaScriptにおけるデータ型
JavaScriptには、値を分類するためのデータ型があり、大きく分けるとプリミティブ型とオブジェクト型に分類されます。データ型は、変数にどのようなデータが格納されているかを決定し、操作の仕方にも影響を与えます。
プリミティブ型
プリミティブ型は、1つの値を表すシンプルなデータ型です。JavaScriptでは次の7つのプリミティブ型があります。
number
1let num = 42;
2let pi = 3.14;
3
4console.log("Value of num:", num);
5console.log("Value of pi:", pi);
number
は数値を扱う型で、整数や浮動小数点数(小数)を表すのに使われます。特定の限界を超える値を扱うと、Infinity
やNaN
(Not-a-Number)が発生します。
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
- JavaScriptでは、数値が浮動小数点数で表現されます。そのため、特定の小数(特に2進数で正確に表せない小数)を正確に表現できないことがあります。
- 金額など正確な計算が求められる場合、このような丸め誤差を回避する必要があります。例えば、
BigInt
を使用するか、toFixed()
を利用して小数点以下の桁数を調整する方法があります。
string
1let greeting = "Hello, world!";
2let char = 'A';
3const message = `"${greeting}" in JavaScript`;
4
5console.log("Value of greeting:", greeting);
6console.log("Value of char:", char);
7console.log("Value of message:", message);
string
は文字列を扱うデータ型で、文字の列を表します。シングルクォート ('
) やダブルクォート ("
) で囲むことで表現します。ES6以降、テンプレートリテラルを使うことで、バックティック()を利用して簡単に変数を埋め込むことができます。変数を埋め込むには、
${}`構文を使います。
boolean
1let isAvailable = true;
2let hasError = false;
3
4console.log("Value of isAvailable:", isAvailable);
5console.log("Value of hasError:", hasError);
boolean
は論理値を表し、true
またはfalse
の2つの値のみを持ちます。条件式の結果やフラグとして使われます。
null
1let result = null;
2
3console.log("Value of result:", result);
null
は明示的に「値がない」ことを示すデータ型です。null
は開発者によって設定され、意図的に空であることを表します。
undefined
1let score;
2let subject = undefined;
3
4console.log("Value of score:", score); // undefined
5console.log("Value of subject:", subject);
undefined
は「未定義」を意味するデータ型です。変数が宣言されたものの、値が割り当てられていない場合に自動的にundefined
が割り当てられます。
bigint
1let bigIntValue = 9007199254740991n;
2let anotherBigInt = 123456789012345678901234567890n;
3
4console.log("Value of bigIntValue:", bigIntValue);
5console.log("Value of anotherBigInt:", anotherBigInt);
bigint
は、大きな整数を扱うためのデータ型です。number
型では表現できない大きな整数もbigint
を使うことで正確に表現できます。bigint
リテラルは数値の末尾にn
を付けて表します。bigint
は、任意のサイズの整数を扱うための型であり、数値の範囲に制限がありません。ただし、bigint
とnumber
の間では直接計算できないため、注意が必要です。
Symbol
1let sym1 = Symbol('id');
2let sym2 = Symbol('id');
3
4console.log("sym1 === sym2:", sym1 === sym2); // false
Symbol
は一意な識別子を作るためのデータ型です。Symbol()
を使って作成し、オブジェクトのプロパティとして使うことができます。他のプリミティブ型とは異なり、Symbol
は一意の値を持つため、同じ内容でも異なるSymbol
として扱われます。
オブジェクト型
オブジェクト型は、複数の値を格納できるデータ構造です。オブジェクトはキーと値のペアのコレクションであり、プロパティやメソッドを持つことができます。
Object
1let person = {
2 name: "John",
3 age: 30,
4 isEmployee: true
5};
6console.log(person.name); // John
Object
は、プロパティ(キーと値のペア)の集合で、さまざまな型のデータを格納できます。オブジェクトは波括弧{}
で表し、各プロパティは:
でキーと値を結びます。
Array
1let numbers = [10, 20, 30];
2console.log(numbers[0]); // 10
3console.log(numbers[1]); // 20
4console.log(numbers[2]); // 30
5console.log(numbers[3]); // undefined
Array
は、複数の値を順序付きで保持するリストです。配列は角括弧[]
で表し、値はカンマ,
で区切られます。各要素には0から始まるインデックスでアクセスします。
Function
1function greet(name) {
2 return "Hello, " + name;
3}
4console.log(greet("Alice")); // Hello, Alice
- 関数は一種のオブジェクトで、コードの再利用可能なブロックです。関数は、
function
キーワードを使って定義できます。
その他のオブジェクト型
- JavaScriptには他にも
Date
、RegExp
、Map
、Set
などの組み込みのオブジェクト型があります。これらは、特定の用途に応じてデータを扱います。
型の変換
JavaScriptでは、暗黙的および明示的な型変換が頻繁に行われます。
暗黙的な型変換
- JavaScriptは異なる型同士を演算するときに、自動的に型を変換することがあります。
1let result = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
- この例では、数値の
5
が文字列に暗黙的に変換され、結果は文字列"55"
となります。
明示的な型変換
- 開発者が明示的に型を変換することもできます。
1let num = "123";
2let convertedNum = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
- この例では、
Number()
関数を使用して、文字列"123"
を明示的に数値123
に変換しています。
型のチェック
JavaScriptでは typeof
演算子を使って、変数のデータ型を確認できます。
1// Output: The type of 42 is: number
2console.log('The type of 42 is:', typeof 42);
3
4// Output: The type of 42 is: bigint
5console.log('The type of 42n is:', typeof 42n);
6
7// Output: The type of "hello" is: string
8console.log('The type of "hello" is:', typeof "hello");
9
10// Output: The type of true is: boolean
11console.log('The type of true is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol() is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {} is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
まとめ
- プリミティブ型には
number
、string
、boolean
、null
、undefined
、symbol
があります。 - オブジェクト型には
Object
、Array
、Function
などがあります。 - 型の自動変換や明示的な変換が行われるため、適切にデータ型を理解することが重要です。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。