このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

Boolean.prototype.toString()

Baseline 広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2015年7月以降、すべてのブラウザーで利用可能です。

toString()Boolean 値のメソッドで、指定された論理値を表す文字列を返します。

試してみましょう

const flag1 = new Boolean(true);

console.log(flag1.toString());
// 予想される結果: "true"

const flag2 = new Boolean(1);

console.log(flag2.toString());
// 予想される結果: "true"

構文

js
toString()

引数

なし。

返値

指定された論理値を表す文字列です。

解説

Boolean オブジェクトは ObjecttoString メソッドを上書きしており、 Object.prototype.toString() を継承していません。Boolean 値の場合、toString メソッドは論理値の文字列表現を返します。この文字列は "true" または "false" のどちらかです。

この toString() メソッドは、その this 値が Boolean プリミティブまたはラッパーオブジェクトであることが要求されます。 this 値がそれ以外の場合、論理値への変換を試みることなく TypeError が発生します。

Boolean には [Symbol.toPrimitive]() メソッドがないため、 JavaScript は文字列を期待するコンテキストで Boolean オブジェクトが使用された場合(例:テンプレートリテラル など)、自動的に toString() メソッドを呼び出します。ただし、論理値のプリミティブは、文字列への変換を行う際に toString() メソッドを参照しません。代わりに、元の toString() 実装と同じアルゴリズムを使用して直接変換されます。

js
Boolean.prototype.toString = () => "Overridden";
console.log(`${true}`); // "true"
console.log(`${new Boolean(true)}`); // "Overridden"

toString() の使用

js
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"

仕様書

仕様書
ECMAScript® 2027 Language Specification
# sec-boolean.prototype.tostring

ブラウザーの互換性

関連情報