-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
63 lines (40 loc) · 2.07 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
---
title: Boolean.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Boolean/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Boolean.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Boolean")}} values returns a string representing the specified boolean value.
{{EmbedInteractiveExample("pages/js/boolean-tostring.html")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the specified boolean value.
## Description
The {{jsxref("Boolean")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit
{{jsxref("Object.prototype.toString()")}}. For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`.
The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to boolean values.
Because `Boolean` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation.
```js
Boolean.prototype.toString = () => "Overridden";
console.log(`${true}`); // "true"
console.log(`${new Boolean(true)}`); // "Overridden"
```
## Examples
### Using toString()
```js
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.toString()")}}