DEV Community

Pankaj Singh
Pankaj Singh

Posted on

🎯 Type Coercion in JavaScript

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
Image description

📌 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
Image description

📌 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"
Image description

📌 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 ( === )

Image description

Top comments (0)