# Type Coercion

Type coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion.

Why is JS so weird : don't break the web

ref : https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/

# Implicit

Implicit type coercion. (Because JS is weakly-typed language)


1 == null
2/5'
null + new Date()
if (value) {} //value is coerced to boolean
1
2
3
4
5

# Explicit

Explicit type coercion(or type casting)

Number(value)
1

# Three Types of conversion

  1. to string

    String(123) // explicit
    123 + ''    // implicit
    
    1
    2
  2. to boolean

    Boolean(2)          // explicit
    if (2) { ... }      // implicit due to logical context
    !!2                 // implicit due to logical operator
    2 || 'hello'        // implicit due to logical operator
    
    1
    2
    3
    4

    falsy values

    Boolean('')           // false
    Boolean(0)            // false     
    Boolean(-0)           // false
    Boolean(NaN)          // false
    Boolean(null)         // false
    Boolean(undefined)    // false
    Boolean(false)        // false
    
    1
    2
    3
    4
    5
    6
    7

    truthy values

    Boolean({})             // true
    Boolean([])             // true
    Boolean(Symbol())       // true
    !!Symbol()              // true
    Boolean(function() {})  // true
    
    1
    2
    3
    4
    5
  3. to number

    Number('123')   // explicit
    +'123'          // implicit
    123 != '456'    // implicit
    4 > '5'         // implicit
    5/null          // implicit
    true | 0        // implicit
    
    1
    2
    3
    4
    5
    6

    examples

    Number(null)                   // 0
    Number(undefined)              // NaN
    Number(true)                   // 1
    Number(false)                  // 0
    Number(" 12 ")                 // 12
    Number("-12.34")               // -12.34
    Number("\n")                   // 0
    Number(" 12s ")                // NaN
    Number(123)                    // 123
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

    ![image-20210129154700500](./Type Coercion.assets/image-20210129154700500.png)

# Special Rules

  1. When applying == to null or undefined, numeric conversion does not happen. null equals only to null or undefined, and does not equal to anything else.

    null == 0               // false, null is not converted to 0
    null == null            // true
    undefined == undefined  // true
    null == undefined       // true
    
    1
    2
    3
    4
  2. NaN does not equal to anything even itself

# Type coercion for objects

  • simplest case is boolean conversion: any non-primitive value is always coerced to true, no matter if an object or an array is empty or not
  • Objects are converted to primitives via the internal [[ToPrimitive]] method, which is responsible for both numeric and string conversion.

ValueOf and toString methods are declared on Object.prototype

  1. If input is already a primitive, do nothing and return it.

  2. Call input.toString(), if the result is primitive, return it.

  3. Call input.valueOf(), if the result is primitive, return it.

  4. If neither input.toString() nor input.valueOf() yields primitive, throw TypeError.

# Examples

true + false             // 1
12 / "6"                 // 2
"number" + 15 + 3        // 'number153'
15 + 3 + "number"        // '18number'
[1] > null               // true
"foo" + + "bar"          // 'fooNaN'
'true' == true           // false
false == 'false'         // false
null == ''               // false
!!"false" == !!"true"    // true
['x'] == 'x'             // true 
[] + null + 1            // 'null1'
[1,2,3] == [1,2,3]       // false
{}+[]+{}+[1]             // '0[object Object]1'
!+[]+[]+![]              // 'truefalse'
new Date(0) - 0          // 0
new Date(0) + 0          // 'Thu Jan 01 1970 02:00:00(EET)0'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

![image-20210129155855396](./Type Coercion.assets/image-20210129155855396.png)

# Arrays are objects

var arr = [ ];

arr[0] = "Zero";

arr[-1] = "Minus One";

arr['prop'] = true;

arr.says = "Hello";
// Mr. JavaScript, I'm not feeling so good...

console.log(arr); //-> [ "Zero", -1: "Minus One", prop: true, says: "Hello" ]
1
2
3
4
5
6
7
8
9
10
11
12
Last Updated: 3/1/2021, 9:19:08 PM