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のデータ型一覧

Last updated at Posted at 2024-08-23

はじめに

JavaScriptは「動的型付け(Dynamic Typing)」で変数の型が実行時に決定される。
JAVAの「静的型付け(Static Typing)」とは違って型を明示的に宣言する必要はない。

ただし、どのようなデータ型があるか理解は必要なので基本的なことだが整理する。
また、「動的型付け(Dynamic Typing)」と「静的型付け(Static Typing)」の違いについても簡単に整理する。

データ型

プリミティブ型

数値(Number)

let num = 1;
console.log(typeof num); // 出力: "number"

長整数(BigInt)

let bigInt = 1234567890123456789012345678901234567890n;
console.log(typeof bigInt); // 出力: "bigint"

文字列(String)

let str = "Hello, World!";
console.log(typeof str); // 出力: "string"

ブール(Boolean)

let isTrue = true;
console.log(typeof isTrue); // 出力: "boolean"

未定義(Undefined)

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

ヌル(Null)

let nullVar = null;
// プリミティブ型"null"が"object"になるのは初期から存在するJavascriptのバグらしい
console.log(typeof nullVar); // 出力: "object"

シンボル(Symbol)

let sym = Symbol('description');
console.log(typeof sym); // 出力: "symbol"

オブジェクト型

オブジェクト(Object)

let obj = { name: 'Mayumi', age: 25 };
console.log(typeof obj); // 出力: "object"

配列(Array)

let arr = [1, 2, 3, 4, 5];
console.log(typeof arr); // 出力: "object"

関数(Function)

function greet() {
  console.log('Hello, World!');
}
console.log(typeof greet); // 出力: "function"

クラス(Function)

class MyClass {
    constructor() {
        this.name = 'example';
    }
}
console.log(typeof MyClass); // 出力: "function"

日付(Date)

let now = new Date();
console.log(typeof now); // 出力: "object"

正規表現(RegExp)

let regex = /ab+c/;
console.log(typeof regex); // 出力: "object"

プリミティブ型とオブジェクト型

プリミティブ型:
 - 単一の値を持つ基本的なデータ型
 - 値そのものを直接格納
オブジェクト型:
 - 複数の値をキーと値のペアとして格納できる複雑なデータ型
 - 値の格納された値(メモリ上のアドレス)を参照格納

動的型付けと静的型付けの違いによる大きな特徴

JavaScriptは「動的型付け(dynamic typing)」で変数の型を明示的に宣言せず使用する。
JAVAは「静的型付け(Static Typing)」で変数の型を明示的に宣言して使用する。
上記特徴により関数を他の関数として定義したり、そもそも型の変換すら可能。

所感として、

  • 処理途中で性質(関数や型)を変えるのは可読性を下げ不具合の原因になる印象が強い
  • 動的型付けの特徴を積極的に機会は多くなさそうと感じるが違いの理解は必要そう
// 関数定義
function greet(name) {
  return `Hello, ${name}!`;
}
// 関数呼び出し
console.log(greet('Mayumi')); // 出力: Hello, Mayumi!

// 関数修正
function greet(name) {
  return `Goodbye, ${name}!`;
}
// 関数呼び出し
console.log(greet('Mayumi')); // 出力: Goodbye, Mayumi!

// 関数を文字列型の変数に変更
greet = "Mayumi!";
// 変数の内容を出力
console.log(greet); // 出力: Mayumi!
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?