> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/type/convert.md).

# type conversion

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [type](/web/js/val/type.md) ⟩ conversion

{% hint style="success" %}
When JS <mark style="color:yellow;">**expects**</mark> a [boolean](/web/js/val/prim/boolean.md), a **value of&#x20;**<mark style="color:red;">**any**</mark>**&#x20;**<mark style="color:yellow;">**type**</mark> **can be supplied**, and JS will <mark style="color:purple;">**convert**</mark> it <mark style="color:yellow;">**as needed**</mark>. The same is true for <mark style="color:red;">**all**</mark>**&#x20;**<mark style="color:yellow;">**types**</mark>.

```javascript
// ⭐ explicit type conversion
Number(' 012'),    // 12
String(34),        // '34'
Boolean({}),       // true

// ⭐ implicit type conversion
+' 012',    // === Number(' 012')
34 + '',    // === String(34)
!!{},       // === Boolean({})
```

{% endhint %}

{% tabs %}
{% tab title="🗺️" %}

* replit： [type conversion table](https://replit.com/@pegasusroe/type-conversion#index.js) (require： [TableMaker](/web/appendix/custom/class/tablemaker.md))

```javascript
┌── (primitive?)
│                              (-> number)   (-> string)
│  x          desc                    +x     String(x)
────────────────────────────────────────────────────────────────────
✅ null                                  0   "null"                 
────────────────────────────────────────────────────────────────────
✅ undefined                           NaN   "undefined"            
────────────────────────────────────────────────────────────────────
✅ 0                                     0   "0"                    
✅ Infinity                       Infinity   "Infinity"             
✅ NaN                                 NaN   "NaN"                  
────────────────────────────────────────────────────────────────────
✅ ""          empty str                 0   ""                     
✅ "1.2"       numeric                 1.2   "1.2"                  
✅ "one"       non-numeric             NaN   "one"                  
────────────────────────────────────────────────────────────────────
✅ true                                  1   "true"                 
✅ false                                 0   "false"                
────────────────────────────────────────────────────────────────────
❌ {a:1}                               NaN   "[object Object]"      
❌ []          empty arr                 0   ""                     
❌ [6]         one numeric               6   "6"                    
❌ ['a']       any other               NaN   "a"                    
❌ new Date                  1667314617317   "Tue Nov 01 2022 14:...
❌ /regex/                             NaN   "/regex/"              
────────────────────────────────────────────────────────────────────
❌ () => {}                            NaN   "() => {}"             
❌ class {}                            NaN   "class {}"             
────────────────────────────────────────────────────────────────────
```

{% endtab %}

{% tab title="🧨" %}
{% hint style="danger" %} <mark style="color:red;">**can't**</mark>**&#x20;**<mark style="color:purple;">**convert**</mark>:exclamation:

* [BigInt](/web/js/val/prim/bigint.md) <mark style="color:red;">**->**</mark> [Number](/web/js/val/prim/num.md):exclamation:(:point\_right: [<mark style="color:red;">**TypeError**</mark>](/web/js/err/type/no-bigint-to-num.md) )
* [Symbol](/web/js/val/prim/symbol.md) <mark style="color:red;">**->**</mark> [Number](/web/js/val/prim/num.md):exclamation:(:point\_right: [<mark style="color:red;">**TypeError**</mark>](/web/js/err/type/no-sym-to-num.md) )
  {% endhint %}
  {% endtab %}

{% tab title="⭐️" %}
{% hint style="success" %}

* <mark style="color:blue;">`isNaN(x)`</mark> will try to <mark style="color:purple;">**convert**</mark> <mark style="color:blue;">`x`</mark> to a <mark style="color:yellow;">**number**</mark> first:exclamation:
* <mark style="color:blue;">`Number.isNaN(x)`</mark> <mark style="color:red;">**never**</mark>**&#x20;**<mark style="color:yellow;">**do**</mark>**&#x20;**<mark style="color:purple;">**conversions**</mark>.
  {% endhint %}

{% hint style="success" %}
[**convert**](/web/js/grammar/op/logical.md) any [value](/web/js/val.md) to [Boolean](/web/js/val/prim/boolean.md).

```javascript
!!x    // any -> true/false, same as Boolean(x)
```

{% endhint %}

{% hint style="success" %}
[**convert**](/web/js/grammar/op/arithmetic/unary.md) any [value](/web/js/val.md) to [Number](/web/js/val/prim/num.md).

```javascript
+x    // any -> number, same as `Number(x)`
```

{% endhint %}

{% hint style="info" %} <mark style="color:red;">**any**</mark> [<mark style="color:yellow;">**non-nullish**</mark>](/web/js/val/prim/nullish.md) value has [**.toString()**](/web/js/val/obj/convert/.tostring.md) method, usually equivalent to [<mark style="color:blue;">**String**</mark>](/web/js/val/prim/str.md)**().**
{% endhint %}
{% endtab %}

{% tab title="🔴" %}

* <mark style="color:yellow;">**operators**</mark>
  * [unary plus (+)](/web/js/grammar/op/arithmetic/unary/+.md) - any -> number (except symbol, bigint)
  * [double tilde (\~\~)](/web/js/grammar/op/arithmetic/bitwise/not/double-tilde.md) - nearest integer towards zero.
  * not not (!!) - any -> bool.
* <mark style="color:yellow;">**type conversions**</mark>
  * [converting objects](/web/js/val/obj/convert.md)
    * :beginner: [object -> primitive conversion](/web/js/val/obj/convert/obj-to-prim.md)&#x20;
  * :ring: [falsy](/web/js/val/type/falsy.md)
    {% endtab %}

{% tab title="👥" %}

* :information\_source: <mark style="color:purple;">**type conversion**</mark> is <mark style="color:yellow;">**involved**</mark> in [sloppy equality (==)](/web/js/grammar/op/relational/equal/sloppy-equality.md)
* :information\_source: <mark style="color:purple;">**type conversion**</mark> is <mark style="color:yellow;">**involved**</mark> in [comparison operator](/web/js/grammar/op/relational/compare.md).
* :warning: <mark style="color:yellow;">**values**</mark> that try to <mark style="color:purple;">**convert**</mark> to a <mark style="color:yellow;">**number**</mark> may result in [NaN](/web/js/val/prim/num/special/nan.md):exclamation:
* :no\_entry: <mark style="color:yellow;">**possible**</mark>**&#x20;**<mark style="color:red;">**errors**</mark>**：**
  * [<mark style="color:red;">**TypeError**</mark>](/web/js/err/type.md)：[<mark style="color:yellow;">**cannot convert BigInt to Number**</mark>](/web/js/err/type/no-bigint-to-num.md):exclamation:
  * [<mark style="color:red;">**TypeError**</mark>](/web/js/err/type.md)：[<mark style="color:yellow;">**cannot convert Symbol to Number**</mark>](/web/js/err/type/no-sym-to-num.md):exclamation:
    {% endtab %}

{% tab title="💈" %}
replit： [type conversion examples](https://replit.com/@pegasusroe/type-conversion-examples#index.js)

```javascript
let n = NaN;

8 + " cats",    // "8 cats"   (8 -> '8')
n + " dogs",    // "NaN dogs" (NaN -> 'NaN')

'3' * '8',      // 24         ('3' -> 3, '8' -> 8)
4 - "a",        // NaN        ('a' -> NaN)
```

{% endtab %}

{% tab title="📗" %}

* [ ] [JavaScript: The Definitive Guide](/web/master/ref/javascript-the-definitive-guide.md) ⟩&#x20;
  * [ ] 3.4 Boolean Values
  * [x] 3.9 Type Conversions ⟩ 3.9.2 Explicit Conversions
    {% endtab %}

{% tab title="📘" %}

* [ ] [JavaScript data types and data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) ⟩ [Type coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion)
* [ ] String ⟩ [String coercion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion)
* [ ] [Object.prototype.toString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) - object to string.
* [ ] [Object.prototype.valueOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) - object to (primitive) value, if exists.
  {% endtab %}

{% tab title=" 🗣" %}

* [In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?](https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals)
  {% endtab %}
  {% endtabs %}
