35% Discount on Residential Proxies for 9 months - use code WING35 at checkout

Get The Deal

Proxywing.com

arrow icon

Type Coercion in JavaScript

Type Coercion in JavaScript

JavaScript is a loosely typed language, which means that it can coerce values of one data type into another automatically. Type coercion in JavaScript is usually seen as a feature, but it also results in confusing bugs if not clearly understood, especially developers used to other languages like Python. 

What is Type Coercion?

Type coercion or type conversions is the implicit or automatic conversion of values from one data type to another. For instance, JavaScript may convert a string to a number or booleans to strings, depending on the context. Type coercion is one of the unique features of Javascript when compared to several other coding languages like Python. 

How Does Type Coercion Work?

Type coercion in JavaScript works in two manners:

  • Implicit Coercions: With the implicit type or implicit conversions, JavaScript automatically converts types, such as 1 + “2” becoming “12” (a string) and this is the case for all operators. That means Javascript will automatically convert the data types even if it is not intended. 
  • Explicit Coercion: With the explicit type, the developer explicitly converts a type using functions such as String(), Number(), or Boolean().

Type Coercion Errors

Unintended type coercion can result in perplexing outcomes. For instance “5” – 1 returning 4 (since the string is converted to a number) or null == undefined being true, yet null === undefined being false. When this happens, it can often lead to difficult-to-locate bugs unlike with other languages like Python.

Examples

  • 1 + “2” → “12” (number + string → string)
  • “5” * 2 → 10 (string → number) • true + 1 → 2 (boolean → number)
  • null == undefined → true
  • [] + {} → “[object Object]” 

Understanding type coercion in Javascript helps write more predictable and bug-free JavaScript code. Use strict equality (===) and explicit conversions to avoid surprises.