このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
Boolean.prototype.toString()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
toString() はBoolean 値のメソッドで、指定された論理値を表す文字列を返します。
In this article
試してみましょう
const flag1 = new Boolean(true);console.log(flag1.toString());// 予想される結果: "true"const flag2 = new Boolean(1);console.log(flag2.toString());// 予想される結果: "true"構文
toString()引数
なし。
返値
指定された論理値を表す文字列です。
解説
Boolean オブジェクトはObject のtoString メソッドを上書きしており、Object.prototype.toString() を継承していません。Boolean 値の場合、toString メソッドは論理値の文字列表現を返します。この文字列は"true" または"false" のどちらかです。
このtoString() メソッドは、そのthis 値がBoolean プリミティブまたはラッパーオブジェクトであることが要求されます。this 値がそれ以外の場合、論理値への変換を試みることなくTypeError が発生します。
Boolean には[Symbol.toPrimitive]() メソッドがないため、 JavaScript は文字列を期待するコンテキストでBoolean オブジェクトが使用された場合(例:テンプレートリテラル など)、自動的にtoString() メソッドを呼び出します。ただし、論理値のプリミティブは、文字列への変換を行う際にtoString() メソッドを参照しません。代わりに、元のtoString() 実装と同じアルゴリズムを使用して直接変換されます。
Boolean.prototype.toString = () => "Overridden";console.log(`${true}`); // "true"console.log(`${new Boolean(true)}`); // "Overridden"例
>toString() の使用
const flag = new Boolean(true);console.log(flag.toString()); // "true"console.log(false.toString()); // "false"仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-boolean.prototype.tostring> |