> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/type-conversions.md).

# Type Conversions

## ToString

```javascript
let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string "true"
alert(typeof value); // string
```

## ToNumber

運算是跟函式都可以轉換成數字。

```javascript
alert( "6" / "2" ); // 3, operator strings are converted to numbers

let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number
```

如果轉換的值不是數字，會顯示 `NaN`。

```javascript
let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed
```

轉換數字的規則：

| Value            | Becomes…                                                                                                                                                                    |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `undefined`      | `NaN`                                                                                                                                                                       |
| `null`           | `0`                                                                                                                                                                         |
| `true and false` | `1` and `0`                                                                                                                                                                 |
| `string`         | Whitespaces from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is “read” from the string. An error gives `NaN`. |

\+ 運算符號是例外，如果其中一個值是 `string` 會變成字串相加，而不是轉換成數字。

```javascript
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
```

## ToBoolean

轉換布林值規則：

| Value                                 | Becomes… |
| ------------------------------------- | -------- |
| `0`, `null`, `undefined`, `NaN`, `""` | `false`  |
| any other value                       | `true`   |

```javascript
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
```
