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 値のメソッドで、指定された論理値を表す文字列を返します。
試してみましょう
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> |
ブラウザーの互換性
Loading…