Type coercion in JavaScript - a glance
#javascript
JavaScript is a dynamically typed language. It means you don't have to explicitly assign data types to the variables. For declaring variables we have special keywords let, var and const. These keywords can declare any variable having any data type. JavaScript has eight basic data types: Number, String, BigInt, Boolean, null, undefined, Object, and Symbol. Except for Object, all others are primitive data types. A primitive data type contains only one value.
Let's discuss the type-coercion in JavaScript. A/c to MDN web docs, "Type coercion is the automatic or implicit conversion of values from one data type to another". It is different from type conversion in the sense that it is IMPLICIT.
Three basic types of type conversions are -
1. String Conversion:
It encloses the data type assigned, by quotation marks.
2. Number Conversion:
Below is the list when any datatype is converted into Number.
x | Number(x)
3. Boolean Conversion:
Boolean(truthy-value) returns true
Boolean(falsy - value) returns false
Recommended by LinkedIn
Note: false, 0, -0, 0n, empty string, null, undefined, NaN all are falsy values, except them, all are truthy values.
TYPE COERCIONS IN JS
In the primitive data-types except for symbol, type coercion is done in many ways:
3. For other comparison operators (<, >, <=, >=): First JavaScript coerces the values into number and then checks the equality operator. In case of Strings, Unicode comparison is done which you can check at following link - Comparisons (javascript.info).
NOTE: NaN is not a data-type, but is a special numeric value which always returns false for all comparisons/operations. Exception- NaN**0 returns 1.
4. For Logical Operators (&&, ||, !, ??): There are four Logical Operators in JavaScript. For first three the operands are converted into number and then the resultant value is returned in the form of same data-type. Whole concept of short-circuiting is based on this.