JavaScriptでboolean型の true / false を文字列に変換する場面は、フォームデータの送信、API通信、ログ出力、UIラベルの表示など多岐にわたります。
この記事では、String()、.toString()、テンプレートリテラル、JSON.stringify() など5つの変換方法を比較し、逆変換やカスタム文字列変換、TypeScriptでの型安全な実装、さらに実務でハマりやすい落とし穴まで徹底解説します。
この記事で学べること
String()・.toString()・テンプレートリテラル・文字列連結・JSON.stringify() の5つの変換方法
- 各方法のパフォーマンスと null / undefined 安全性の比較
- 文字列
"true" / "false" → boolean への逆変換テクニック
- 三項演算子によるカスタムラベル変換(「はい」/「いいえ」等)
- TypeScript での型安全な変換ユーティリティ
- フォームデータ・API通信での実務的な活用パターン
"false" が truthy になる落とし穴と対処法
String() 関数で boolean を文字列に変換する
String() はJavaScriptのグローバル関数で、あらゆる型を文字列に変換できます。boolean の変換では最も安全で推奨される方法です。
JavaScript – String() で boolean → 文字列
const boolTrue = true;
const boolFalse = false;
const strTrue = String(boolTrue); // "true"
const strFalse = String(boolFalse); // "false"
console.log(strTrue); // "true"
console.log(typeof strTrue); // "string"
// null / undefined も安全に変換できる
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
実行結果
true
string
null
undefined
ポイント:String() は null や undefined を渡してもエラーにならず、安全に文字列化できます。型が不確定な値を扱う場面で最も信頼性が高い方法です。
.toString() メソッドで boolean を文字列に変換する
.toString() は Boolean オブジェクトのプロトタイプメソッドで、true → "true"、false → "false" に変換します。
JavaScript – .toString() で変換
const isActive = true;
const isHidden = false;
console.log(isActive.toString()); // "true"
console.log(isHidden.toString()); // "false"
// typeof で確認
console.log(typeof isActive.toString()); // "string"
注意:null や undefined に対して .toString() を呼ぶと TypeError が発生します。値が確実に boolean であることが保証されている場合にのみ使用してください。
JavaScript – .toString() の注意点
let value = null;
// TypeError: Cannot read properties of null
try {
value.toString();
} catch (e) {
console.log(e.message); // "Cannot read properties of null (reading 'toString')"
}
// 安全に使うにはオプショナルチェーンを活用
console.log(value?.toString() ?? "N/A"); // "N/A"
実行結果
Cannot read properties of null (reading 'toString')
N/A
テンプレートリテラルで boolean を文字列に変換する
ES6(ES2015)で導入されたテンプレートリテラル(バッククォート `)を使うと、${} 内の値が自動的に文字列化されます。他の文字列と組み合わせる場合に特に便利です。
JavaScript – テンプレートリテラルで変換
const isLoggedIn = true;
const isAdmin = false;
// 単純な変換
const str = `${isLoggedIn}`; // "true"
// 他の文字列と組み合わせ
console.log(`ログイン状態: ${isLoggedIn}`);
console.log(`管理者権限: ${isAdmin}`);
// null / undefined も安全
console.log(`値: ${null}`); // "値: null"
console.log(`値: ${undefined}`); // "値: undefined"
実行結果
ログイン状態: true
管理者権限: false
値: null
値: undefined
ポイント:テンプレートリテラルは内部で String() と同等の変換を行うため、null / undefined でもエラーになりません。ログ出力やメッセージ組み立てに最適です。
文字列連結(”” + bool)で変換する
空文字列 "" と + 演算子で連結する方法です。JavaScriptの型強制(type coercion)を利用した暗黙的な変換になります。
JavaScript – 文字列連結で変換
const flag = true;
// 空文字列との連結
const str1 = "" + flag; // "true"
const str2 = flag + ""; // "true"
const str3 = "" + false; // "false"
console.log(str1); // "true"
console.log(typeof str1); // "string"
// null / undefined も変換可能
console.log("" + null); // "null"
console.log("" + undefined); // "undefined"
実行結果
true
string
null
undefined
注意:暗黙的な型変換に依存するため、コードの意図が読み取りにくくなることがあります。チーム開発では明示的な String() の方が好まれます。ESLint の no-implicit-coercion ルールで警告対象になる場合もあります。
JSON.stringify() で boolean を文字列に変換する
JSON.stringify() は値をJSON文字列に変換します。boolean 値の場合、true → "true"、false → "false" になりますが、ダブルクォートが含まれない点に注意してください。
JavaScript – JSON.stringify() で変換
const isEnabled = true;
// boolean → JSON文字列
console.log(JSON.stringify(isEnabled)); // "true"
console.log(JSON.stringify(false)); // "false"
// 文字列との違い ― 文字列は引用符が付く
console.log(JSON.stringify("true")); // '"true"' (ダブルクォート付き)
console.log(JSON.stringify(true)); // 'true' (引用符なし)
// オブジェクト内の boolean
const config = { darkMode: true, notifications: false };
console.log(JSON.stringify(config));
// '{"darkMode":true,"notifications":false}'
実行結果
true
false
"true"
true
{"darkMode":true,"notifications":false}
ポイント:JSON.stringify() は単独の boolean 変換よりも、オブジェクトごとJSON化する場面で真価を発揮します。API通信やlocalStorageへの保存時に活用しましょう。
5つの変換方法を徹底比較
ここまで紹介した5つの方法を、安全性・可読性・用途の面で比較します。
| 方法 |
構文 |
null安全 |
可読性 |
推奨場面 |
String() |
String(bool) |
安全 |
高い |
汎用・最も推奨 |
.toString() |
bool.toString() |
危険 |
高い |
型が確実な場合 |
| テンプレートリテラル |
`${bool}` |
安全 |
高い |
文字列への埋め込み |
| 文字列連結 |
"" + bool |
安全 |
低い |
短縮表記(非推奨) |
JSON.stringify() |
JSON.stringify(bool) |
安全 |
中程度 |
API通信・データ保存 |
ポイント:迷ったら String() を使いましょう。null/undefined安全で、コードの意図も明確です。文字列に埋め込む場面ではテンプレートリテラルが自然です。
文字列 "true" / "false" → boolean への逆変換
APIレスポンスやフォーム入力で受け取った文字列を boolean に戻す処理もよく使います。ここでは複数の逆変換パターンを紹介します。
厳密比較による基本パターン
JavaScript – 文字列 → boolean 基本パターン
// パターン1: 厳密比較(最も安全)
const str = "true";
const bool = str === "true"; // true
// パターン2: 大文字小文字を無視
function toBoolean(value) {
return String(value).toLowerCase() === "true";
}
console.log(toBoolean("true")); // true
console.log(toBoolean("True")); // true
console.log(toBoolean("TRUE")); // true
console.log(toBoolean("false")); // false
console.log(toBoolean("abc")); // false
console.log(toBoolean(null)); // false
実行結果
true
true
true
false
false
false
JSON.parse() による逆変換
JavaScript – JSON.parse() で逆変換
// JSON.parse() は "true"/"false" を boolean に変換する
console.log(JSON.parse("true")); // true (boolean)
console.log(JSON.parse("false")); // false (boolean)
// ただし不正な文字列はエラーになる
try {
JSON.parse("True"); // SyntaxError(大文字は不可)
} catch (e) {
console.log(e.message); // Unexpected token...
}
// 安全に使うラッパー関数
function safeParseBool(str) {
try {
const parsed = JSON.parse(str);
return typeof parsed === "boolean" ? parsed : false;
} catch {
return false;
}
}
console.log(safeParseBool("true")); // true
console.log(safeParseBool("false")); // false
console.log(safeParseBool("hello")); // false
実行結果
true
false
Unexpected token...
true
false
false
"true"/"false" 以外のカスタム文字列変換
実務では "true" / "false" ではなく、「はい」/「いいえ」、「ON」/「OFF」、「有効」/「無効」など日本語や任意のラベルに変換したい場面が頻繁にあります。
三項演算子で簡潔に変換する
JavaScript – 三項演算子でカスタムラベル
const isActive = true;
const isSubscribed = false;
// 日本語ラベル
console.log(isActive ? "はい" : "いいえ"); // "はい"
console.log(isSubscribed ? "はい" : "いいえ"); // "いいえ"
// ON / OFF
console.log(isActive ? "ON" : "OFF"); // "ON"
// 有効 / 無効
console.log(isActive ? "有効" : "無効"); // "有効"
// 記号での表現
console.log(isActive ? "✓" : "✗"); // "✓"
console.log(isSubscribed ? "✓" : "✗"); // "✗"
汎用的なラベル変換関数
JavaScript – 汎用ラベル変換関数
// 汎用関数: ラベルのペアを引数で受け取る
function boolToLabel(value, trueLabel = "はい", falseLabel = "いいえ") {
return value ? trueLabel : falseLabel;
}
// マッピングオブジェクトを使うパターン
const labelMap = {
yesNo: { true: "はい", false: "いいえ" },
onOff: { true: "ON", false: "OFF" },
status: { true: "有効", false: "無効" },
check: { true: "✓", false: "✗" },
};
function boolToMappedLabel(value, type = "yesNo") {
return labelMap[type][value];
}
console.log(boolToLabel(true)); // "はい"
console.log(boolToLabel(false, "Active", "Inactive")); // "Inactive"
console.log(boolToMappedLabel(true, "onOff")); // "ON"
console.log(boolToMappedLabel(false, "check")); // "✗"
TypeScript での型安全な boolean → 文字列変換
TypeScriptではジェネリクスやオーバーロードを活用して、型レベルで安全な変換を実現できます。
TypeScript – 型安全な変換ユーティリティ
// 型安全な boolean → 文字列変換
function booleanToString(value: boolean): "true" | "false" {
return String(value) as "true" | "false";
}
// 文字列 → boolean(型ガード付き)
function isBooleanString(value: string): value is "true" | "false" {
return value === "true" || value === "false";
}
function stringToBoolean(value: string): boolean {
if (isBooleanString(value)) {
return value === "true";
}
throw new Error(`Invalid boolean string: ${value}`);
}
// カスタムラベル用のジェネリック型
type BooleanLabels<T extends string, F extends string> = {
trueLabel: T;
falseLabel: F;
};
function boolToCustomLabel<T extends string, F extends string>(
value: boolean,
labels: BooleanLabels<T, F>
): T | F {
return value ? labels.trueLabel : labels.falseLabel;
}
// 使用例
const result = boolToCustomLabel(true, {
trueLabel: "有効",
falseLabel: "無効"
}); // 型: "有効" | "無効"
console.log(result); // "有効"
ポイント:TypeScriptの型ガード(value is "true" | "false")を使えば、変換後の値が型レベルで保証されます。ジェネリクスを使ったカスタムラベル関数は、戻り値の型が自動推論されるため補完も効きます。
null / undefined が混在する場合の安全な変換
実務のコードでは、boolean 値が null や undefined になり得る場面が多々あります。各変換方法の挙動を確認し、安全な処理パターンを紹介します。
各方法の null / undefined 挙動一覧
| 方法 |
null |
undefined |
String() |
"null" |
"undefined" |
.toString() |
TypeError |
TypeError |
`${value}` |
"null" |
"undefined" |
"" + value |
"null" |
"undefined" |
JSON.stringify() |
"null" |
undefined(返り値なし) |
JavaScript – null / undefined の安全な処理
// パターン1: デフォルト値付き変換
function safeBoolToString(value, defaultStr = "false") {
if (value === null || value === undefined) {
return defaultStr;
}
return String(value);
}
// パターン2: Null合体演算子(??)を活用
const value = null;
const str = String(value ?? false); // "false"
// パターン3: Boolean() で正規化してから変換
const input = undefined;
const normalized = String(Boolean(input)); // "false"
console.log(safeBoolToString(true)); // "true"
console.log(safeBoolToString(null)); // "false"
console.log(safeBoolToString(undefined)); // "false"
console.log(str); // "false"
console.log(normalized); // "false"
実行結果
true
false
false
false
false
フォームデータ・API通信での実践的な活用
boolean と文字列の変換は、フォームの送信やREST API との通信で非常に重要です。実務で使えるパターンを紹介します。
フォームデータの処理
JavaScript – フォームデータの boolean 処理
// チェックボックスの値を boolean に変換
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(form);
// チェックボックス: checked なら "on"、未チェックなら存在しない
const agreeRaw = formData.get("agree");
const agree = agreeRaw === "on";
// select の "true"/"false" 文字列を boolean に変換
const notifyStr = formData.get("notify");
const notify = notifyStr === "true";
console.log({ agree, notify });
// { agree: true, notify: false }
});
REST API との通信
JavaScript – API通信での boolean 変換
// ===== APIへの送信(boolean → JSON文字列) =====
async function updateSettings(settings) {
const response = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
// settings = { darkMode: true, notifications: false }
// body = '{"darkMode":true,"notifications":false}'
});
return response.json();
}
// ===== APIからの受信(JSON文字列 → boolean) =====
async function fetchSettings() {
const response = await fetch("/api/settings");
const data = await response.json();
// JSON.parse() が自動で boolean に変換
console.log(typeof data.darkMode); // "boolean"
return data;
}
// ===== URLクエリパラメータの処理 =====
const params = new URLSearchParams(window.location.search);
// クエリパラメータは常に文字列
const debugMode = params.get("debug") === "true";
console.log(debugMode); // ?debug=true → true
localStorage / sessionStorage での保存と復元
JavaScript – localStorage での boolean 保存・復元
// 保存: boolean → 文字列(自動変換)
localStorage.setItem("darkMode", true); // "true" として保存
localStorage.setItem("sound", false); // "false" として保存
// 復元: 文字列 → boolean(手動変換が必要!)
const darkMode = localStorage.getItem("darkMode") === "true";
const sound = localStorage.getItem("sound") === "true";
console.log(darkMode); // true
console.log(sound); // false
// JSON.stringify / JSON.parse でオブジェクトごと保存する方法(推奨)
const settings = { darkMode: true, sound: false, autoSave: true };
localStorage.setItem("settings", JSON.stringify(settings));
const loaded = JSON.parse(localStorage.getItem("settings"));
console.log(loaded.darkMode); // true (boolean)
console.log(loaded.sound); // false (boolean)
実行結果
true
false
true (boolean)
false (boolean)
ポイント:localStorage.setItem() は値を自動的に文字列化しますが、getItem() は文字列のまま返します。boolean に戻すには === "true" の比較か、JSON.parse() が必要です。複数の設定値はオブジェクトごと JSON.stringify() で保存するのが管理しやすくおすすめです。
よくある落とし穴と注意点
boolean と文字列の変換で初心者がハマりやすいポイントをまとめます。
落とし穴1: 文字列 "false" は truthy
JavaScriptでは空文字列以外のすべての文字列は truthy です。これが最もよくある間違いの原因です。
JavaScript – "false" は truthy
const strFalse = "false";
// 間違い: 文字列 "false" は truthy!
if (strFalse) {
console.log("ここが実行される!"); // 実行される
}
// 正しい: 文字列を比較してから判定する
if (strFalse === "true") {
console.log("true のとき");
} else {
console.log("false のとき"); // こちらが実行される
}
// truthy / falsy の確認
console.log(Boolean("false")); // true(空でない文字列は truthy)
console.log(Boolean("")); // false(空文字列は falsy)
console.log(Boolean("0")); // true("0" も truthy!)
実行結果
ここが実行される!
false のとき
true
false
true
注意:if ("false") は true と評価されます。APIやlocalStorageから受け取った文字列を boolean として使う場合は、必ず === "true" で厳密比較してください。
落とし穴2: Boolean() と new Boolean() の違い
JavaScript – Boolean() と new Boolean() の違い
// Boolean() ― プリミティブの boolean を返す(正しい使い方)
const a = Boolean("false");
console.log(a); // true
console.log(typeof a); // "boolean"
// new Boolean() ― Boolean オブジェクトを返す(使わないこと!)
const b = new Boolean(false);
console.log(b); // [Boolean: false]
console.log(typeof b); // "object"(boolean ではない!)
// Boolean オブジェクトは truthy(false でも!)
if (b) {
console.log("truthy!"); // 実行される(false なのに!)
}
実行結果
true
boolean
[Boolean: false]
object
truthy!
落とし穴3: == と === の挙動の違い
JavaScript – == と === の挙動の違い
// == は型変換が発生する(予想外の結果に注意)
console.log(true == "true"); // false("true" → NaN → false)
console.log(true == "1"); // true("1" → 1、true → 1)
console.log(false == "0"); // true("0" → 0、false → 0)
console.log(false == ""); // true("" → 0、false → 0)
console.log(false == "false"); // false("false" → NaN → false)
// === は型変換なし(推奨)
console.log(true === "true"); // false(型が違うので常に false)
console.log(true === true); // true
実行結果
false
true
true
true
false
false
true
注意:true == "true" は false です!== は boolean を数値(0 / 1)に変換してから文字列と比較するため、直感に反する結果になります。boolean と文字列の比較には必ず === を使い、型を揃えてから比較してください。
逆引き早見表 ― やりたいこと別ベストプラクティス
実務で「こういうことがしたい」というケース別に、推奨される方法をまとめました。
| やりたいこと |
推奨コード |
boolean → "true" / "false" |
String(bool) |
| 文字列内に boolean を埋め込む |
`状態: ${bool}` |
| boolean → 「はい」/「いいえ」 |
bool ? "はい" : "いいえ" |
"true" → boolean |
str === "true" |
| API送信用のJSON化 |
JSON.stringify(obj) |
| localStorage に boolean を保存 |
JSON.stringify() / JSON.parse() |
| null/undefined を安全に文字列化 |
String(value ?? false) |
| URLクエリパラメータから取得 |
params.get("key") === "true" |
まとめ
JavaScriptでboolean型の true / false を文字列に変換する方法と、逆変換、カスタムラベル、実務での活用パターンを解説しました。
この記事のまとめ
String() が最も安全で推奨 ― null/undefined でもエラーにならない
.toString() はシンプルだが null/undefined で TypeError が発生する
- テンプレートリテラル
`${bool}` は文字列埋め込みに最適
- 文字列連結
"" + bool は暗黙的変換のため可読性が低い
JSON.stringify() はAPI通信やデータ保存で活用
- 逆変換は
=== "true" の厳密比較が最も安全
- カスタムラベルは三項演算子
bool ? "はい" : "いいえ" が簡潔
- 文字列
"false" は truthy ― if で直接判定しないこと
- TypeScript では型ガードとジェネリクスで安全な変換を実現できる