TypeScriptにおける`truthy`と`falsy`
この記事ではTypeScriptにおけるtruthy
とfalsy
について説明します。
YouTube Video
TypeScriptにおけるtruthy
とfalsy
TypeScriptにおけるtruthy
とfalsy
の概念は、プログラムの条件判定において非常に重要な役割を果たします。ここでは、これらの概念を理解し、実際にどのように利用されるかについて詳しく説明します。さらに、truthy
やfalsy
の値がどのように扱われるかを理解するために具体的なTypeScriptのコード例も提供します。
truthy
とfalsy
とは?
JavaScriptやTypeScriptにおいて、任意の値は条件式の中で真(true
)または偽(false
)に評価されます。これらの値は論理的に truthy
または falsy
として分類されます。
- **
truthy
**は、条件式の中でtrue
として評価される値です。 - **
falsy
**は、条件式の中でfalse
として評価される値です。
TypeScriptでは、以下の値がfalsy
として扱われます。
- 数値の
0
""
(空の文字列)
これ以外の全ての値はtruthy
として扱われます。
truthy
とfalsy
の具体例
1// Examples of falsy values
2console.log("0 is", Boolean(0) ? "truthy" : "falsy");
3console.log('"" is', Boolean("") ? "truthy" : "falsy");
4console.log("null is", Boolean(null) ? "truthy" : "falsy");
5console.log("undefined is", Boolean(undefined) ? "truthy" : "falsy");
6console.log("NaN is", Boolean(NaN) ? "truthy" : "falsy");
7
8// Examples of truthy values
9console.log("1 is", Boolean(1) ? "truthy" : "falsy");
10console.log('"hello" is', Boolean("hello") ? "truthy" : "falsy");
11console.log("[] is", Boolean([]) ? "truthy" : "falsy");
12console.log('" " (space) is', Boolean(" ") ? "truthy" : "falsy");
truthy
とfalsy
を使った条件分岐
truthy
とfalsy
の概念は、条件分岐やループでよく利用されます。たとえば、if
文やwhile
文では、これらの値を直接利用してシンプルな条件判定を行うことができます。
1// Checking if the length of the array is 0
2let items: string[] = [];
3
4if (items.length) {
5 console.log("The array is not empty");
6} else {
7 console.log("The array is empty");
8}
9
10// Checking if the input value is empty
11let input = "";
12
13if (input) {
14 console.log("Input has value");
15} else {
16 console.log("Input is empty"); // This will be executed
17}
??
(Nullish Coalescing)と||
(論理OR)を使ったfalsy
な値の扱い
TypeScriptでは、falsy
な値を扱う際に便利な演算子がいくつか存在します。特にNull合体演算子(Nullish Coalescing Operator, ??
)と論理OR演算子(||
)はよく使われます。
||
(論理OR)
論理OR演算子は、falsy
な値をデフォルト値に置き換えるために使われます。ただし、falsy
とされる全ての値(null
やundefined
だけでなく、0
や空文字列""
など)も対象になります。
1let username = "";
2let displayName = username || "Guest";
3// Since username is empty, "Guest" is assigned
4
5console.log(displayName); // "Guest"
??
(Nullish Coalescing)
Null合体演算子は、null
またはundefined
に対してのみデフォルト値を適用し、他のfalsy
な値(0
や空文字列""
など)はそのまま扱います。
1let username2 = "";
2let displayName2 = username2 ?? "Guest";
3// The empty string is retained
4// since username2 is not null or undefined
5
6console.log(displayName2); // ""
truthy
とfalsy
に関連する落とし穴
truthy
やfalsy
の概念を理解する際に気をつけるべきポイントは、意図しない値がfalsy
として扱われる可能性があることです。例えば、0
や空文字列""
は正当な値ですが、条件文ではfalsy
と見なされるため、誤った判定を引き起こす可能性があります。
1let score = 0;
2
3if (score) {
4 console.log("You have a score!"); // This will not be executed
5} else {
6 console.log("No score available"); // This will be executed
7}
このようなケースでは、厳密な比較演算子を使用することで、0
やfalse
を正確に判定できます。
1let score = 0;
2
3if (score === 0) {
4 console.log("Score is zero"); // Correctly evaluated
5}
falsy
とNaN
に関する落とし穴
NaN
は比較演算子で他の値、さらには自分自身とも等しくないという性質を持っているため、特別な取り扱いが必要です。
1console.log("NaN === NaN:", NaN === NaN); // false
そのため、NaN
を正確に検出するために Number.isNaN()
を使用するのが安全です。
1// Bad Example
2let value = parseInt("0");
3if (!value) {
4 console.log("Value is NaN(Incorrect)"); // Incorrectly treats 0 as NaN
5}
6
7// Good Example
8let value2 = parseInt("hello");
9if (Number.isNaN(value2)) {
10 console.log("Value is NaN(Correct)"); // Correctly identifies NaN
11}
このように、NaN
は自分自身とすら等しくないため、NaN
との比較は常に false
を返します。代わりに Number.isNaN()
を使用することで、より信頼性のある判定が可能になります。
結論
TypeScriptにおけるtruthy
とfalsy
の概念は、非常に便利ですが、特定の値(特に0
や空文字列)に注意する必要があります。これらの値を条件判定に使用する際は、==
の緩やかな比較ではなく、===
の厳密な比較やNull合体演算子(??
)を適切に使うことで、予期しない挙動を避けることができます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。