Q1. What is Type Coercion in JavaScript?
Type coercion in JavaScript is the automatic or manual conversion of a value from one data type to another. JavaScript performs this conversion when an operation involves different data types.
Since JavaScript is a dynamically typed language, variables do not have fixed types. Because of this, JavaScript sometimes converts values automatically to make operations possible.
Example
Output
Here JavaScript converts number 2 into a string and performs string concatenation.
Since JavaScript is a dynamically typed language, variables do not have fixed types. Because of this, JavaScript sometimes converts values automatically to make operations possible.
Example
console.log("5" + 2);Output
"52"Here JavaScript converts number 2 into a string and performs string concatenation.
Q2. How does JavaScript behave during comparison with Type Coercion?
JavaScript performs type coercion when using the loose equality operator (==). It converts values into the same type before comparison.
Example
Output
JavaScript converts string "5" into number before comparison.
Example
console.log(5 == "5");Output
trueJavaScript converts string "5" into number before comparison.
Q3. What are some common examples of Type Coercion in JavaScript?
Stirng Conversion
Output
Number Conversion
Output
Boolean Conversion
Null and Undefined Behavior
Output
JavaScript treats them as loosely equal but they are different types.
console.log("Hello " + 10);Output
Hello 10Number Conversion
console.log("20" * 2);Output
40Boolean Conversion
console.log(Boolean(0)); // false
console.log(Boolean(1)); // trueNull and Undefined Behavior
console.log(null == undefined);Output
trueJavaScript treats them as loosely equal but they are different types.
Q4. Why can Type Coercion be dangerous in JavaScript?
Type coercion can cause unexpected results and bugs because JavaScript automatically converts values without warning.
Example
Output
This can confuse developers because an empty string and zero are different values logically.
Example
console.log("" == 0);Output
trueThis can confuse developers because an empty string and zero are different values logically.
