# type conversion

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [type](https://lochiwei.gitbook.io/web/js/val/type) ⟩ conversion

{% hint style="success" %}
When JS <mark style="color:yellow;">**expects**</mark> a [boolean](https://lochiwei.gitbook.io/web/js/val/prim/boolean), 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](https://lochiwei.gitbook.io/web/appendix/custom/class/tablemaker "mention"))

```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](https://lochiwei.gitbook.io/web/js/val/prim/bigint "mention") <mark style="color:red;">**->**</mark> [num](https://lochiwei.gitbook.io/web/js/val/prim/num "mention"):exclamation:(:point\_right: [<mark style="color:red;">**TypeError**</mark>](https://lochiwei.gitbook.io/web/js/err/type/no-bigint-to-num) )
* [symbol](https://lochiwei.gitbook.io/web/js/val/prim/symbol "mention") <mark style="color:red;">**->**</mark> [num](https://lochiwei.gitbook.io/web/js/val/prim/num "mention"):exclamation:(:point\_right: [<mark style="color:red;">**TypeError**</mark>](https://lochiwei.gitbook.io/web/js/err/type/no-sym-to-num) )
  {% 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**](https://lochiwei.gitbook.io/web/js/grammar/op/logical) any [..](https://lochiwei.gitbook.io/web/js/val "mention") to [boolean](https://lochiwei.gitbook.io/web/js/val/prim/boolean "mention").

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

{% endhint %}

{% hint style="success" %}
[**convert**](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/unary) any [..](https://lochiwei.gitbook.io/web/js/val "mention") to [num](https://lochiwei.gitbook.io/web/js/val/prim/num "mention").

```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>](https://lochiwei.gitbook.io/web/js/val/prim/nullish) value has [**.toString()**](https://lochiwei.gitbook.io/web/js/val/obj/convert/.tostring) method, usually equivalent to [<mark style="color:blue;">**String**</mark>](https://lochiwei.gitbook.io/web/js/val/prim/str)**().**
{% endhint %}
{% endtab %}

{% tab title="🔴" %}

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

{% tab title="👥" %}

* :information\_source: <mark style="color:purple;">**type conversion**</mark> is <mark style="color:yellow;">**involved**</mark> in [sloppy-equality](https://lochiwei.gitbook.io/web/js/grammar/op/relational/equal/sloppy-equality "mention")
* :information\_source: <mark style="color:purple;">**type conversion**</mark> is <mark style="color:yellow;">**involved**</mark> in [compare](https://lochiwei.gitbook.io/web/js/grammar/op/relational/compare "mention").
* :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](https://lochiwei.gitbook.io/web/js/val/prim/num/special/nan "mention"):exclamation:
* :no\_entry: <mark style="color:yellow;">**possible**</mark>**&#x20;**<mark style="color:red;">**errors**</mark>**：**
  * [<mark style="color:red;">**TypeError**</mark>](https://lochiwei.gitbook.io/web/js/err/type)：[<mark style="color:yellow;">**cannot convert BigInt to Number**</mark>](https://lochiwei.gitbook.io/web/js/err/type/no-bigint-to-num):exclamation:
  * [<mark style="color:red;">**TypeError**</mark>](https://lochiwei.gitbook.io/web/js/err/type)：[<mark style="color:yellow;">**cannot convert Symbol to Number**</mark>](https://lochiwei.gitbook.io/web/js/err/type/no-sym-to-num):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](https://lochiwei.gitbook.io/web/master/ref/javascript-the-definitive-guide "mention") ⟩&#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 %}
