Coercion in JavaScript

 

What is Coercion in JavaScript?

In JavaScript, the process of converting the type of a variable into another is called Coercion. This means a variable of string type when changed to a number type due to some process is called coercion of the variable.

let a="34"; //defining a as string type
let b=5; //defining b as a number type
let sum=a+b;
console.log(sum); //345 ??
typeof(sum); //The result would be "string"

In the above code snippet, since the variable a is defined as a string type, it will be considered as a string. Hence JavaScript has coerced the 5 from a number into a string and then concatenated the two values together, resulting in a string of 345. Now, let’s take another case.

let a=34; //defining a as string type
let b=5; //defining b as a number type
let sum=a+b;
console.log(sum); //39
typeof(sum); //The result would be "number"

The above code makes it clear that since both the variables were declared as a Number, the resulting sum would also be of type Number.

Types of Coercion

There are 2 types of coercion.

  • Implicit Coercion
  • Explicit Coercion

Implicit Coercion

Implicit Coercion means the conversion between types of variables that do not happen explicitly but due to the program’s flow.

let a="34"; //defining a as string type
let b=a*1; //defining b as a number type
typeof(b); // "number" due to Implicit Coercion

Explicit Coercion

The conversion of a variable from one type to another explicitly in code is known as Explicit Coercion.

let a="34"; //defining a as string type
let b=Number(a); //defining b as a number type
typeof(b); // "number" due to Explicit Coercion.

Comments

Popular posts from this blog

HISTORY MYSTERY: ORIGIN OF THE TERM DEBUGGING