What is Type Conversion?
In JavaScript, type conversion refers to changing a value from one data type to another. It is an essential concept because JavaScript is a dynamically typed language, meaning you don't need to specify data types explicitly.
There are two types of type conversions:
- Implicit Conversion (Type Coercion) - Done automatically by JavaScript.
- Explicit Conversion - Done manually in code using conversion functions.
Implicit Type Conversion (Type Coercion)
JavaScript automatically converts data types when needed. This is called type coercion.
Example 1: String and Number Concatenation
let result = '10' + 5;
console.log(result);
Output:
105
Explanation: The number 5
is implicitly converted to a string, and the result is string concatenation: '10' + '5' = '105'
.
Example 2: Subtracting a String from a Number
let difference = '10' - 2;
console.log(difference);
Output:
8
Explanation: Here, JavaScript converts the string '10'
to the number 10
and then performs subtraction.
Q: Why does addition with a string lead to concatenation, while subtraction leads to numerical operation?
A: JavaScript treats +
as both a concatenation and arithmetic operator. If either operand is a string, it prefers string concatenation. For other operators like -
, *
, /
, it defaults to numeric operations.
Explicit Type Conversion
Explicit conversion is when you manually convert a value using JavaScript functions like Number()
, String()
, or Boolean()
.
Example 3: Convert String to Number
let str = "42";
let num = Number(str);
console.log(num);
console.log(typeof num);
Output:
42 number
Explanation: The Number()
function converts the string "42"
to a number.
Example 4: Convert Number to String
let val = 100;
let strVal = String(val);
console.log(strVal);
console.log(typeof strVal);
Output:
100 string
Explanation: The String()
function converts the number 100
to a string.
Example 5: Convert Values to Boolean
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
Explanation: Boolean()
converts values to either true
or false
based on their "truthiness".
Truthy and Falsy Values
When converting to Boolean
, JavaScript considers the following values as falsy:
false
0
""
(empty string)null
undefined
NaN
All other values are truthy.
Quick Summary
- JavaScript automatically performs implicit conversion when needed (e.g.,
'5' + 1
becomes'51'
). - Use
Number()
,String()
, andBoolean()
for explicit conversion. - Be cautious with
+
operator due to its dual nature.
Practice Question
What will be the output of the following?
console.log('5' * '2');
Answer:
10
Why? Both strings are implicitly converted to numbers before performing multiplication.