As the name implies, type conversion is the process of converting a value from one type to another, Values in JavaScript can be of different types. You could have a number, string, object, boolean etc. Sometimes, you may want to convert data from one type to another to perform a certain operation.
Implicit Type Conversion is also known (and more commonly referred to) as Coercion while Explicit Type Conversion is also known as Type Casting. Let’s look at these two conversions in detail.
Implicit Type Conversion (Coercion) in JavaScript
There are some operations that you might try to execute in JavaScript which are literally not possible. For example, look at the following code:
let sum = 35 + "hello"
JavaScriptHere, you’re trying to add a number and a string. This is, practically speaking, not possible. You can only add numbers (sum) together or add strings (concatenate) together.
So what happens here if you try to run the code?
Instead of JavaScript throwing an error, it coerces the type of one value to fit the type of the other value so that the operation can be carried out.
In this case, using the + sign with a number and a string, the number is coerced to a string, then the + sign is used for a concatenation operation.
let sum = 35 + "hello"
console.log(sum)
// 35hello
console.log(typeof sum)
// string
JavaScriptThis is an example of coercion where the type of one value is converted (coerced) to fit the other so that the operation can continue.
With the plus sign, it is more ideal for the number to be converted to a string (instead of the string converted to a number). This is because a number equivalent to a string is NaN
but a string equivalent for a number, say 15
, is "15"
– so it makes more sense to concatenate two strings than to sum a number and NaN
.
Look at another example below:
let times = 35 * "hello"
console.log(times) // NaN
JavaScriptHere, we use times * for a number and a string. There’s no operation with strings that involves multiplication, so here, the ideal coercion is from string to number (as numbers have compatible operations with multiplication).
But since a string (in this case, "hello"
) is converted to a number (which is NaN
) and that number is multiplied by 35
, the final result is NaN
.
Coercion is usually caused by different operators used between different data types:
let string = ""
let number = 40
let boolean = true
console.log(!string)
// true - string is coerced to boolean `false`, then the NOT operator negates it
console.log(boolean + string)
// "true" - boolean is coerced to string "true", and concatenated with the empty string
console.log(40 + true)
// 41 - boolean is coerced to number 1, and summed with 40
JavaScriptOne very common operator that causes coercion is the loose equality operator (==, or double equals).
Double Equality and Coercion
In JavaScript, there’s both the double equality operator (== which is called the loose equality operator) and the triple equality operator (=== strict equality operator). You use both operators to compare values’ equality.
How the Loose Equality Operator Works
The loose equality operator does a loose check. It checks if values are equal. The types are not a focus for this operator – only the values are the major factor.
What I mean here is 20, a value of a number
type, and “20”, a value of the string
type, are equal when you use double equality:
let variable1 = 20
let variable2 = "20"
console.log(variable1 == variable2)
// true
JavaScriptThough the types are not equal, the operator returns true
because the values are equal. What happens here is coercion.
When you use the loose equality operator with values of different types, what happens first is coercion. Again, this is where one value is converted to the type that fits the other, before the comparison occurs.
In this case, the string “20” is converted to a number type (which is 20
) and then compared with the other value, and they are both equal.
Another example:
let variable1 = false
let variable2 = ""
console.log(variable1 == variable2)
// true
JavaScriptHere, variable1
is the value false (boolean type) and variable2
“” (an empty string, of the string type). Comparing both variables with the double equality returns true
. That’s because the empty string is coerced to a boolean type (which is ).
How the Strict Equality Operator Works
This operator does a strict check – that is, it strictly checks the values compared, as well as the types. Type coercion does not occur here, so there are no unexpected answers. Here are the examples from above:
let variable1 = 20
let variable2 = "20"
console.log(variable1 === variable2)
// false
let variable3 = false
let variable4 = ""
console.log(variable3 === variable4)
// false
JavaScriptIn the case of variable1
and variable2
, they have the same values, but the types are not the same. So the triple equality returns false
.
In the case of variable3
and variable4
, they have the same values (if one is converted to the type of the other) but the types are not the same, so the triple equality returns false
this time, too.
Explicit Type Conversion (Type Casting) in JavaScript
Here, you explicitly convert a value from one type to another.
The type conversion that you do manually is known as explicit type conversion.
In JavaScript, explicit type conversions are done using built-in methods
For example, to convert a number to a string:
let number = 30
let numberConvert = String(number)
console.log(numberConvert)
// "30"
console.log(typeof numberConvert)
// string
JavaScriptAnother example is to convert a number to a boolean:
let number = 30
let numberConvert = Boolean(number)
console.log(numberConvert)
// true
console.log(typeof numberConvert)
// boolean
JavaScriptAnd one more example, to convert a boolean to a string:
let boolean = false
let booleanConvert = String(boolean)
console.log(booleanConvert)
// "false"
console.log(typeof booleanConvert)
// string
JavaScriptIn these examples, we explicitly convert a value from one type to another.
Conclusion
Type conversion is a fundamental concept in JavaScript, crucial for effectively managing and manipulating data across different types. Understanding both implicit and explicit type conversions is key to writing robust, error-free JavaScript code. Implicit conversion (coercion) allows JavaScript to be flexible and forgiving, but it can also lead to subtle bugs if not fully understood. Explicit conversion (type casting), on the other hand, offers more control and predictability, making your code’s intentions clear and preventing unintended side effects. As a best practice, prefer explicit type conversion to maintain code clarity and reduce the risk of errors, especially in complex applications.
Frequently Asked Questions
Ans: Type conversion in JavaScript refers to changing the data type of a value to another, such as converting a string to a number, a number to a boolean, or any other type conversion. It can be either implicit (coercion) or explicit (type casting).
Q2. What is Implicit Type Conversion?
Ans: Implicit type conversion, or coercion, occurs when JavaScript automatically converts one data type to another, such as converting numbers to strings during concatenation or strings to numbers in arithmetic operations, without explicitly being instructed to do so by the programmer.
Q3. Can you give an example of Implicit Type Conversion?
Ans: Yes, an example of implicit type conversion is concatenating a string with a number:let result = 'The number is: ' + 5;
console.log(result); // "The number is: 5"
Here, JavaScript implicitly converts the number 5 to a string before concatenation.
Q4. What is Explicit Type Conversion?
Ans: Explicit type conversion, or type casting, involves manually converting values from one type to another using built-in functions like String()
, Number()
, Boolean()
, etc.
Q5. What is the difference between
==
and ===
in JavaScript? Ans: The ==
operator (loose equality) compares two values for equality after converting them to a common type (if they are not already of the same type), while the ===
operator (strict equality) compares both the value and the type without converting them, requiring both to be identical for it to return true.