Type Conversion in JavaScript (implicit and explicit coercion)

Author
By Darío Rivera
Posted On in Javascript

Most of the time, JavaScript performs type conversions without us even noticing it. Today, we will see these conversions that happen almost without our consent and other types of conversions over which we do have control.

String Conversion

This conversion occurs every time a string is required at some point in the script. Since JavaScript takes care of this conversion, it is usually called implicit coercion. An example of this conversion occurs when we try to add a string and a number.

let a = 5;
let b = '6';
let sum = a + b;  // '56'
typeof sum;       // string

It is also possible to explicitly convert a value to a string using the String wrapper object. This type of conversion using the wrapper object is usually called explicit coercion.

let b = true;
value = String(b);  // now value is a string "true"
typeof value;       // string

Numeric Conversion

Numeric conversion occurs every time a number is required at some point in the script. An example of this conversion occurs when two numeric strings are mathematically operated. Interestingly, this occurs with all operators except the + sign (see string conversion).

let a = '3';
let b = '4';
let times = a * b;  // 12
typeof times;       // number

For other types of data, the conversion turns out to be similar to how that type was converted with the wrapper object.

undefined + 6;   // NaN, since undefined is NaN
null + 25;       // 25, since null=0
true + true;     // 2, since true=1

It is also possible to explicitly convert a value to a number using the Number wrapper object.

let c = '4';
let num = Number(c);  // 4
typeof num;           // number

Boolean Conversion

Boolean conversion occurs every time a boolean is required at some point in the script. An example of this conversion may occur in decision statements.

let name = 'John Doe';
if (name) {
    console.info('Hello ' + name);
}

It is also possible to explicitly convert a value to a boolean using the Boolean wrapper object.

let b = 1;
let c = Boolean(b);  // true
typeof c;            // boolean

If this wrapper object thing sounds a bit strange to you, I invite you to review the post Wrapper Objects in Javascript where you can get a more complete appreciation of the behavior of these objects. You can also observe a little more in detail the conversion of common values in JavaScript.


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.