| この記事の要点 |
|
基本
const score = 75;
if (score >= 80) {
console.log("A");
} else if (score >= 60) {
console.log("B");
} else {
console.log("C");
}
else if はいくつでも並べられ、else は省略できます。上から順に評価され、最初に真になった枝だけが実行されます。
波かっこを省略しない
// 1 行なら省略できるが…
if (ok) console.log("OK");
// あとから行を足すと壊れる
if (ok)
console.log("OK");
console.log("これは条件に関係なく必ず実行される"); // ← インデントに騙される
// 常に波かっこを付ける
if (ok) {
console.log("OK");
console.log("こちらは条件付き");
}
真偽の判定ルール
| 偽(falsy)— この 8 つだけ | 真(truthy)— それ以外すべて |
|---|---|
false 0 -0 0n "" null undefined NaN | "0" "false" " " [] {} -1 Infinity 関数 … |
if ("0") console.log("真"); // 実行される(空でない文字列)
if ([]) console.log("真"); // 実行される(空配列でも真)
if ({}) console.log("真"); // 実行される
// 空配列の判定
const items = [];
if (items.length === 0) console.log("空です");
// if (!items) は永遠に成立しない
// 空オブジェクトの判定
if (Object.keys(obj).length === 0) console.log("空です");
// 数値の 0 が有効値のとき
const count = 0;
if (count) console.log("ここには来ない"); // 0 は偽
if (count !== undefined) console.log("こちら"); // 意図どおり
[] と {} が真なのは他の言語から来ると最も間違えやすい点です。「空かどうか」は必ず length やキーの数で判定してください。
== ではなく === を使う
console.log(1 == "1"); // true 型を変換してから比べる
console.log(1 === "1"); // false
console.log(0 == ""); // true
console.log(0 == false); // true
console.log(null == 0); // false ← null は数値に変換されない
console.log(null == undefined); // true ← この 2 つだけは等しい
console.log(NaN == NaN); // false NaN はどれとも等しくない
// NaN の判定
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("abc")); // false(変換しない。こちらを使う)
console.log(isNaN("abc")); // true (変換してしまう古い関数)
例外的に == null はnull と undefined をまとめて判定する書き方として広く使われています。それ以外は === にしてください。
if (value == null) { // null か undefined
// ...
}
if (value === null || value === undefined) { // 同じ意味(明示的)
}
入力値は文字列で来る
const input = document.querySelector("#age");
if (input.value === 20) { } // 常に false("20" と 20 は別)
if (Number(input.value) === 20) { } // 正しい
// 空欄と 0 を区別する
if (input.value === "") console.log("未入力");
if (Number(input.value) === 0) console.log("0 が入力された");
// 数値に変換できるか確かめる
const n = Number(input.value);
if (input.value.trim() === "" || Number.isNaN(n)) {
console.log("数値を入力してください");
}
input.value dataset localStorage の値はすべて文字列です。比較の前に Number() で変換してください。
複数条件
const user = { age: 25, active: true, plan: "pro" };
if (user.age >= 20 && user.active) { } // かつ
if (user.plan === "pro" || user.plan === "biz") { } // または
if (!user.active) { } // でない
// 候補が多いなら includes
if (["pro", "biz", "ent"].includes(user.plan)) { }
// 短絡評価を安全チェックに使う
if (user && user.profile && user.profile.name) { }
if (user?.profile?.name) { } // オプショナルチェーン(推奨)
// 条件が長いときは名前を付ける
const isAdult = user.age >= 20;
const isPaid = ["pro", "biz"].includes(user.plan);
if (isAdult && isPaid && user.active) { }
// 連鎖比較は書けない
if (0 < user.age < 10) { } // 常に true になる(誤り)
if (0 < user.age && user.age < 10) { } // 正しい
0 < age < 10 は (0 < age) が true になり、true < 10 が 1 < 10 として評価されるため常に真になります。エラーにならないぶん厄介です。
三項演算子と ?? の使い分け
const label = score >= 60 ? "合格" : "不合格";
// || は falsy すべてを弾くので 0 や "" が消える
const count1 = input || 10; // input が 0 でも 10 になる
const count2 = input ?? 10; // input が null / undefined のときだけ 10
// ?? と || は混ぜて書けない(かっこが必要)
// const x = a ?? b || c; // SyntaxError
const x = (a ?? b) || c;
ネストを浅くする
// ネストが深い
function price(user) {
if (user) {
if (user.active) {
if (user.vip) return 800;
return 1000;
}
}
return 0;
}
// 早期 return で平らにする
function price(user) {
if (!user?.active) return 0;
return user.vip ? 800 : 1000;
}
// 値を比べるだけの分岐はオブジェクトに置き換えられる
const LABELS = { start: "開始", stop: "停止" };
const label = LABELS[command] ?? "不明";
else if が 5 個以上続いて値を比べているだけなら、オブジェクトの引き当てか switch に置き換えると見通しが良くなります(switch)。
関連
子ページ
子ページはありません
同階層のページ
- if文
- switch
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスのソフト一覧|Blender・Metasequoiaと用途別の選び方
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- CKEditor 5 の導入手順と使い方(npm・CDN・licenseKey) 2026-11-26 19:21:38
- UE5「古いHLODを検出」が出る条件とHLODのリビルド方法 2026-11-26 19:21:37
- iOS シミュレーターの画面を拡大・縮小する方法(Xcode 27) 2026-11-26 19:14:05
- Apache NetBeans 32 を Windows に導入する方法(ZIP版・JDK) 2026-11-26 19:14:05
- Julia Genie.jl 入門 — Rails ライク Web フレームワーク完全ガイド 2026-11-26 19:01:42
- Node.js の Windows インストール完全ガイド — 公式 / nvm-windows / Chocolatey / winget 2026-11-26 19:01:42
- Unity Standard Assets とは — 廃止された公式アセットと代替 2026-11-26 19:01:42
- FTP プロトコル完全ガイド - ポート 21/20 / Active / Passive / FTPS / SFTP の違い 2026-11-26 19:01:41
- Oracle Database Buffer Cache(バッファキャッシュ)の仕組みとチューニング 2026-11-26 19:01:41
- zstd (Zstandard) の使い方 - 高速高圧縮の現代標準 | CWiki IT 2026-11-26 19:01:40
- usermod コマンド — グループ追加 -aG の落とし穴とユーザー属性変更まとめ 2026-11-26 19:01:40
- Zstandard(.zst)とは|速度と圧縮率を両立する圧縮形式 2026-11-26 19:01:40
- Cygwin とは? WSL2 / Git Bash / MinGW との違いと現代的な選び方 2026-11-26 19:01:39
- Eclipse で Tomcat を起動するボタンを出す手順(Servers ビュー + サーバー登録) 2026-11-26 19:01:38
- WSL2のインストール手順|wsl --install・Ubuntu・.wslconfig設定 2026-11-26 18:59:55