JavaScript

変数と型

JavaScript

var、let、const とデータ型

var / let / const

変数宣言の違いとスコープ

declarations.js javascript
// const: 再代入不可(推奨デフォルト)
const PI = 3.14159;
const user = { name: 'Alice' };
user.name = 'Bob'; // ✅ プロパティは変更可
// user = {};      // ❌ 再代入は不可

// let: 再代入可能
let count = 0;
count = count + 1; // ✅

// var: 関数スコープ、巻き上げあり(非推奨)
var old = 'avoid';

// スコープの違い
function scopeDemo() {
    var x = 'function scope';
    let y = 'block scope';
    if (true) {
        var x = 'same variable!'; // 上書きされる
        let y = 'new variable';   // 別の変数
        const z = 'block only';
    }
    console.log(x); // 'same variable!'
    console.log(y); // 'block scope'
    // console.log(z); // ❌ ReferenceError
}

データ型

プリミティブ型と参照型

types.js javascript
// プリミティブ型(値渡し)
const num    = 42;
const float  = 3.14;
const str    = 'hello';
const bool   = true;
const nothing = null;
const undef  = undefined;
const big    = 9007199254740991n; // BigInt
const sym    = Symbol('unique');   // Symbol

// 参照型(参照渡し)
const arr = [1, 2, 3];
const obj = { key: 'value' };
const fn  = () => {};

// 型の確認
typeof 42         // 'number'
typeof 'hello'    // 'string'
typeof true       // 'boolean'
typeof undefined  // 'undefined'
typeof null       // 'object' ← 歴史的バグ
typeof []         // 'object'
typeof {}         // 'object'
typeof function(){} // 'function'

// 正確な型チェック
Array.isArray([1,2,3])    // true
Object.prototype.toString.call(null) // '[object Null]'
value instanceof Date     // Date インスタンス判定

型変換

明示的・暗黙的な型変換

coercion.js javascript
// 明示的な変換
Number('42')    // 42
Number('')      // 0
Number('abc')   // NaN
Number(true)    // 1
Number(false)   // 0
Number(null)    // 0
Number(undefined) // NaN

String(42)      // '42'
String(null)    // 'null'
String(true)    // 'true'

Boolean(0)      // false
Boolean('')     // false
Boolean(null)   // false
Boolean(undefined) // false
Boolean(NaN)    // false
Boolean(0n)     // false
// 上記以外はすべて true(Truthy)

// 整数・浮動小数点変換
parseInt('42px')    // 42
parseInt('0xff', 16) // 255
parseFloat('3.14m') // 3.14
(3.14159).toFixed(2) // '3.14'

// NaN のチェック
isNaN('hello')     // true(型変換あり)
Number.isNaN('hello') // false(型変換なし・推奨)
Number.isNaN(NaN)     // true

テンプレートリテラル

バッククォートで文字列の補間と複数行

template-literals.js javascript
const name = 'Alice';
const age  = 30;

// 文字列補間
const msg = `こんにちは、${name}さん! ${age}歳ですね。`;

// 複数行
const html = `
  <div class="card">
    <h2>${name}</h2>
    <p>年齢: ${age}</p>
  </div>
`;

// 式の評価
const result = `合計: ${10 * 5 + 3}`; // '合計: 53'
const status = `状態: ${age >= 18 ? '成人' : '未成年'}`;

// タグ付きテンプレート
function highlight(strings, ...values) {
    return strings.reduce((result, str, i) =>
        result + str + (values[i] ? `<mark>${values[i]}</mark>` : ''),
    '');
}
const output = highlight`${name}${age}歳です。`;