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のnullとundefinedの違い・使い分け

Last updated at Posted at 2025-06-03

JavaScriptのnullとundefinedの違いと使い分け

はじめに

日頃他の言語を触っているので、JavaScriptでundefinedなる概念に遭遇し困惑しました。
この記事ではnullundefinedの概念について、適切な使い分け方法を説明します。
※本記事の一部ソースは生成AIの出力を使用しています。

要約

  • undefined: JavaScript が自動的に割り当てる「未定義」状態
  • null: 開発者が意図的に設定する「空の値」
  • 基本原則: 明示的に「空」を表現したい場合はnull、それ以外はundefined

undefinedとは

undefinedは、変数が宣言されているが値が代入されていない状態を表します。

let x; // 宣言のみ
console.log(x); // undefined

const obj = { name: "太郎" };
console.log(obj.age); // undefined(存在しないプロパティ)

function test() {
    // 明示的にreturnしない
}
console.log(test()); // undefined

nullとは

nullは、開発者が意図的に「値が存在しない」ことを表現するために使用します。

let user = null; // 意図的に「値なし」を設定

// APIからデータを取得する前の初期状態
let apiData = null;

// DOM要素が見つからない場合
const element = document.getElementById('nonexistent');
console.log(element); // null

主な違い

型の違い

console.log(typeof undefined); // "undefined"
console.log(typeof null);      // "object"

等価性の比較

console.log(null == undefined);  // true(緩い等価性)
console.log(null === undefined); // false(厳密等価性)

console.log(null === null);           // true
console.log(undefined === undefined); // true

真偽値への変換

console.log(Boolean(null));      // false
console.log(Boolean(undefined)); // false

// どちらもfalsyな値
if (!null) console.log("nullはfalsy");
if (!undefined) console.log("undefinedもfalsy");

実際の使い分け

オブジェクトプロパティの初期化

const user = {
    name: "田中太郎",
    email: "tanaka@example.com",
    avatar: null,        // まだ設定されていない(意図的な空)
    // lastLoginは定義しない(undefined)
};

console.log(user.avatar);    // null
console.log(user.lastLogin); // undefined

関数の戻り値

function findUser(id) {
    const users = [
        { id: 1, name: "太郎" },
        { id: 2, name: "花子" }
    ];
    
    const found = users.find(user => user.id === id);
    return found || null; // 見つからない場合は明示的にnullを返す
}

DOM操作

const button = document.getElementById('submit-btn');

if (button === null) {
    console.log("ボタンが見つかりません");
} else {
    button.addEventListener('click', handleClick);
}

よくある間違い

typeofでのnullチェック

// 間違い
if (typeof value === 'null') {
    // このブロックは実行されない
}

// 正しい
if (value === null) {
    console.log("nullです");
}

JSON.stringifyでの扱い

const obj = {
    a: null,
    b: undefined,
    c: "hello"
};

console.log(JSON.stringify(obj));
// {"a":null,"c":"hello"}
// undefinedのプロパティは削除される

まとめ

項目 undefined null
設定者 JavaScript自動 開発者が明示的
意味 未定義状態 意図的な空の値
typeof "undefined" "object"
使用場面 初期化前、存在しないプロパティ 明示的に空を表現

重要なポイント

  1. undefinedはJavaScriptが自動的に設定する未定義状態
  2. nullは開発者が意図的に設定する空の値
  3. 厳密等価性(===)を使用して型も含めて比較する
  4. 現代のJavaScriptでは???.演算子を活用する

参考文献

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?