Modern Javascript Basics Part - I

Type Coercion

Subscribe to my newsletter and never miss my upcoming articles

This is the first post that forms the beginning of a number of related blog posts on the basics and syntax of the javascript language. These blog posts will dive into a number of small topics that are normally neglected by developers but are crucial to their careers.

The first of these posts will dive into type coercion in javascript.

Type coercion is where the javascript engine has to work with two different datatypes E.g string with a number and has to convert one data type to another ignorer to work with the two.

This conversion has a priority order that begins with stings, Number, and finally Boolean.

1. String coercion;

When presented with an operation with both strings and numbers, javascript converts the number(s) into a string(s) in order to work with two district variables. Example;

// jshint esversion:6
let num1 = 20;
console.log(typeof(num1)); //number
let num2 = " Twenty one";
console.log(typeof(num2)); // string
let sum = num1 + num2;
console.log(sum); //20 Twenty one
console.log(typeof(sum)); // string

From the example above, num1 is of type number while num2 is of type string which is confirmed by using the inbuilt function (typeof()). When the two are added together, javascript gives priority to the string datatype by converting the first variable (num1) into a string and the result (sum) is a string.

2. Number coercion

The second priority is given to the number datatypes in javascript. This means that when presented with a number and a boolean datatype, javascript converts the boolean datatype into a number and evaluates the equation. Example;

// jshint esversion:6
let num1 = 20;
console.log(typeof(num1)); //number
let num2 = true;
console.log(typeof(num2)); // boolean
let sum = num1 + num2;
console.log(sum); //21
console.log(typeof(sum)); // number

From the above example, the first variable was of type number while the second was boolean. Adding the two distinct variables forces javascript to give priority to the number datatype by converting the boolean into a number in this case true becomes 1 which when added to the first variable which was a number (20) results in a number datatype (21).

THANK YOU so much for taking your time to read this article. A lot more tips and posts related to javascript are on the way and to get notified when they do, follow me on Twitter and I'd really appreciate it. If you are feeling more generous I'll not stop you from buying me a cup of coffee. coffee_black.png

No Comments Yet