LVLPATH

日本最強無料プログラミングスクール

PATHSERVICEHANDS ONMANZI
JavaScript文法基礎: 基本的な型

基本的な型

✅ 基本的な型

JavaScriptには基本的な型があります。

型というのは、種類のようなものです。

  • 文字列: string型
  • 数値: number型
  • 真偽値: boolean型
  • 未定義: undefined
  • 存在しない: null

✅ 型の確認方法

typeof 演算子(オペレーター)を使います。

const num = 123;
console.log(typeof num);
// number

const string = "123";
console.log(typeof string);
// string

const bool = true;
console.log(typeof bool);
// boolean

✅ 文字列の型

const str = "文字列"
const str2 = "文字列2"
const str3 = "123" + "456";

console.log(str, str2, str3);
// 文字列 文字列2 123456

✅ 数値の型

const num1 = 123;
const num2 = 234 + 555;
const num3 = 12 * 12;

console.log(num1, num2, num3);
// 123 789 144

✅ 真偽値の型

const bool1 = true;
const bool2 = false;
const bool3 = true && false;
const bool4 = true || false;

console.log(bool1, bool2, bool3, bool4);
// true false false true

✅ undefined

日本語にすると未定義です。

文字通り、定義されていない値です。

nullと違うのはnullは「何もない」(何も入れていない)という意味合いで使いますが、undefinedは「定義されていない」といったニュアンスで使われます。

const v = undefined;

console.log(v);
// undefined

const v2 = {a: 1}
console.log(v2.b);
// undefined

✅ null

nullは何も値を入れていないという意味合いで使います。

「何も値を値を変数に代入していない」という場合には、undefinedよりもnullを使う傾向にあります。

const a = null;

console.log(a);
// null

✅ まとめ

  • 基本的な型の種類を知っておく
    • 数値
    • 文字列
    • 真偽値
    • undefined
    • null
  • 型の確認方法を知っておく
    • typeof を使う
お問い合わせ