Type Coercion in JavaScript

Type Coercion in JavaScript

ยท

2 min read

Table of contents

No heading

No headings in the article.

Type Coercion is process of automatic or implicit conversion of value from one data type to another. Conversion from Number to String , String to Number, Boolean to Number and so on. Type coercion occurs when different types of operators are applied to the values

  • Number to String

Anything added to string first JavaScript convert it into string and then concatenates both the strings.

Note : It occur only with "+" operator

// Number to String conversion
let a = 10 + "20"
let b = "10" + 20
let c = undefined + "20"
let d = true + "10-1"

console.log(a)  // 1020
console.log(b)  // 1020
console.log(c)  // undefined20
console.log(d)  // true10-1
  • String to Number

When operation like subtraction( - ), multiplication( * ), division( / ), modulus (%) is performed first JavaScript convert it into number then apply these operations

Note : The string should be a Number

// String to Number
let a = "20" - 10
let b = "5" - 10
let c = "70-1" * 1
let d = "20" / 3
let e = "20" % 2

console.log(a) // 10
console.log(b) // -5
console.log(c) // NaN (not a number), how ? check the note
console.log(d) // 6.67 (approx)
console.log(e) // 0
  • Boolean to Number

When a boolean is added to a Number, boolean value is converted to number as 0 for "false" and 1 for "true"

// Boolean to Number
let a = true + 10
let b = false + 10
let c = 10 * true
let d = 10 / false

console.log(a) // 11
console.log(b) // 10
console.log(c) // 10
console.log(d) // Infinity
  • Equality Operator

The equality ( == ) is used to compare value irrespective of their type. This happen by coercion of Non-Number to Number data type

Note : To avoid type coercion, use the triple-equals operator ( === )

// Equality Operator
let a = ( 11 == "11" )
let b = ( false == 0 )
let c = ( true == 1 )
let d = ( true == "true" )
let e = ( true === 1 )  // To avoid type coercion

console.log(a) // true
console.log(b) // true
console.log(c) // true
console.log(d) // false
console.log(e) // false
ย