JavaScript初心者でもわかるnullとundefined
JavaScriptにおける null と undefined の違い
意味の違い
- null は、意図的に値を設定していないことを表します。つまり、「空」であることを明示的に示すために使用されます。
- undefined は、以下のいずれかの状況を表します。
- 変数が宣言されているが、値が代入されていない
- オブジェクトのプロパティが存在しない
- 関数の引数が渡されていない
- 関数が値を返さない
つまり、null
は意図的な空の値である一方、undefined
は意図せず発生する値の欠如を表します。
型の違い
- null は
object
型 - undefined は
undefined
型
型チェックを行う際には、この違いに注意する必要があります。
console.log(typeof null); // "object"
console.log(typeof undefined); // "undefined"
使い分け
- 変数に意図的に空の値を設定したい場合は
null
を使用します。 - 変数が宣言されているが、値がまだ代入されていないことを示したい場合は
undefined
を使用します。 - オブジェクトのプロパティが存在しないことを示したい場合は
undefined
を使用します。 - 関数が値を返さない場合は
undefined
を返します。
その他
==
演算子では、null
とundefined
は互いに等価とみなされます。
例
// 変数に空の値を設定
let name = null;
// 関数の引数が渡されていない
function sayHello(name) {
if (name === undefined) {
console.log("Hello, world!");
} else {
console.log(`Hello, ${name}!`);
}
}
sayHello(); // "Hello, world!"
// オブジェクトのプロパティが存在しない
const person = {
name: "John Doe",
};
console.log(person.age); // undefined
まとめ
null
と undefined
はどちらも値を表す特殊な値ですが、異なる意味を持ちます。それぞれの意味と使い分けを理解して、正しく使用しましょう。
// 変数に空の値を設定
let name = null;
// 関数の引数が渡されていない
function sayHello(name) {
if (name === undefined) {
console.log("Hello, world!");
} else {
console.log(`Hello, ${name}!`);
}
}
sayHello(); // "Hello, world!"
// オブジェクトのプロパティが存在しない
const person = {
name: "John Doe",
};
console.log(person.age); // undefined
// 型チェック
console.log(typeof null); // "object"
console.log(typeof undefined); // "undefined"
// 比較演算子
console.log(null == undefined); // true
console.log(null === undefined); // false
このコードを実行することで、null
と undefined
のそれぞれの意味、型、使い分け、比較演算子の結果を確認することができます。
これらの資料を読むことで、null
と undefined
についてより深く理解することができます。
null と undefined の違いを理解するその他の方法
これらのチュートリアルでは、null
と undefined
の違いをわかりやすく説明しています。
これらのツールは、null
と undefined
の違いを理解するのに役立つインタラクティブな学習体験を提供します。
これらの書籍では、null
と undefined
を含む JavaScript の基礎知識について詳しく説明されています。
実践
- 簡単なプログラムを作成し、
null
とundefined
の値を出力してみましょう。
まとめ
null
と undefined
の違いを理解するには、さまざまな方法があります。自分に合った方法を見つけて、理解を深めていきましょう。
javascript null undefined