DEV Community

Learner
Learner

Posted on

Type Coercion & Type Casting

Type Coercion in javascript is a process where a type is converted to another type explictly or implicitly. When it happens explictly, it is known as type casting and in case of implicit conversion, it is known as type coercion.

There are 3 types of conversion:


  1. String Conversion
  2. Number Conversion
  3. Boolean Conversion

  4. String Conversion

Explicit Conversion

String(123) => “123”
String(true) => “true”

Implicit Conversion

It happens automatically with + operator, when any one of the operands is a string, the other is also converted to the string.

Examples:

“number” + 12 => “number12”

  • Boolean Conversion

Explicit Conversion

Boolean(1) => true
Boolean(“”) => false

Implicit Conversion

It triggers with all the logical operators ( ||, &&, !) 

Examples

!!23 => true 

true && (!!23 == true) 


3. Number Conversion

Explicit Conversion

Number(“”) => 0
Number(“123”) => 123

Implicit Conversion

It is triggered with any of the below operators

Comparison operators (> < <= =>)
  • Arithmetic Operators ( - + * / % )
  • Bitwise operators
  • Unary + operator
  • Loose equality operator

Top comments (0)