JavaScript Interview Question #11
What is type coercion in JavaScript?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
Type coercion is the conversion of a value from one type to another. JavaScript can perform implicit coercion automatically during certain operations, or developers can perform explicit conversion using functions such as Number, String, and Boolean.
Detailed Explanation
Type coercion is the conversion of a value from one type to another. JavaScript can perform implicit coercion automatically during certain operations, or developers can perform explicit conversion using functions such as Number, String, and Boolean.
Implicit coercion is especially important with the + operator and loose equality. Interview candidates should understand the rules rather than assuming all operators convert values in the same way.
Code Example
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
const age = Number("30");
const text = String(100);
const enabled = Boolean(1);
console.log(age, text, enabled);