Module 20 : Javascript Type Conversion and Coercion
📘 1. Introduction to Types in JavaScript
JavaScript is a dynamically typed language, meaning variable types are determined at runtime.
🔹 JavaScript Data Types:
javascript
code
// Primitive types string, number, boolean, null, undefined, symbol, bigint // Object types Object, Array, Function, Date, RegExp, etc.
🔸 2. Type Conversion vs Type Coercion
Aspect
Type Conversion (Explicit)
Type Coercion (Implicit)
Who does it?
You, the programmer
JavaScript engine (automatically)
How?
Using functions like String(), Number()
Occurs during operations like +, ==
Predictable?
Yes
Sometimes confusing or unexpected
Example
Number("42") → 42
"5" * 2 → 10 (string coerced to number)
🔸 3. Explicit Type Conversion (Type Casting)
✅ To String
javascript
code
String(123) // "123" (123).toString() // "123" true + "" // "true"
✅ To Number
javascript
code
Number("42") // 42 parseInt("42px") // 42 parseFloat("3.14") // 3.14 +"42" // 42
✅ To Boolean
javascript
code
Boolean("") // false Boolean("Hello") // true Boolean(0) // false !!"hi" // true
⚠️ Falsy Values
javascript
code
false, 0, "", null, undefined, NaN
🔸 4. Implicit Type Coercion (Automatic)
JavaScript tries to help by converting types for you.
✅ String Coercion with +
javascript
code
"5" + 2 // "52" true + "yes" // "trueyes"
✅ Number Coercion with other operators
javascript
code
"5" * 2 // 10 "10" - 1 // 9 "5" / 2 // 2.5 null + 1 // 1
✅ Boolean Coercion in logical expressions
javascript
code
!!"hello" // true !!0 // false if ("0") console.log("truthy"); // prints
🔸 5. Equality Comparisons (== vs ===)
✅ == (loose equality): allows coercion
javascript
code
"5" == 5 // true 0 == false // true null == undefined // true
✅ === (strict equality): no coercion
javascript
code
"5" === 5 // false 0 === false // false
✅ Best Practice:
Always use === unless you intentionally want coercion.
🔸 6. Conversion Table (Quick Reference)
Value
To String
To Number
To Boolean
"123"
"123"
123
true
"abc"
"abc"
NaN
true
true
"true"
1
true
false
"false"
0
false
null
"null"
0
false
undefined
"undefined"
NaN
false
[]
""
0
true
{}
"[object Object]"
NaN
true
🔸 7. Practical Examples
Example 1: String concatenation vs arithmetic
javascript
code
console.log("10" + 1); // "101" console.log("10" - 1); // 9
Example 2: Boolean coercion
javascript
code
let x = "hello"; if (x) { console.log("Truthy"); // Output: Truthy }
Example 3: Equality confusion
javascript
code
console.log(false == '0'); // true console.log(false === '0'); // false
🔸 8. Common Pitfalls
"42" > 5 → true (coerces string to number)
null == 0 → false but null >= 0 → true
[] == false → true, [] == ![] → true (confusing behavior)
🔸 9. Best Practices
Use strict equality (===) to avoid unexpected coercion.
Always explicitly convert types when needed.
Use helper functions: Number(), String(), Boolean() instead of relying on JS to guess.
Validate input before performing operations.
🔸 10. Exercises
🔧 Exercise 1: Predict the Output
javascript
code
console.log(5 + "5"); // ? console.log("5" - 2); // ? console.log(true + 1); // ? console.log(false == 0); // ? console.log(null + 5); // ?
💡 Expected Output:
"55", 3, 2, true, 5
🔧 Exercise 2: Type Conversion Practice
javascript
code
let a = "123"; let b = true; let c = "abc"; console.log(Number(a)); // ? console.log(Number(b)); // ? console.log(Number(c)); // ?
💡 Expected: 123, 1, NaN
Activity: Build a Type Checker
Create a small tool in JavaScript that accepts any input and logs:
Type of the input
Type after coercion using +, *, Boolean
Suggestions on what to use (=== or type conversion)
javascript
code
function checkInput(input) { console.log("Original:", input); console.log("Type:", typeof input); console.log("To Number:", Number(input)); console.log("To Boolean:", Boolean(input)); console.log("Using == 5:", input == 5); console.log("Using === 5:", input === 5); } checkInput("5");
🔸 11. Strategy
Explain with visuals: Use diagrams to show how types flow and change during coercion.
Live code walkthroughs: Use the browser console to show changes.
Interactive tools: Use JS Tutor to step through code.
Debate == vs ===: Let guess outputs before revealing coercion behavior.
Assign exercises focusing on type safety in code.
🔸12.Advanced Insights
JavaScript uses the ECMAScript ToPrimitive and ToNumber abstract operations under the hood.
Loose equality (==) uses a complex algorithm involving these steps:
Convert objects to primitives
Coerce types using rules
Compare
📚 Reference: ECMAScript Language Specification – Abstract Equality
🔚 Conclusion
Understanding JavaScript type conversion and coercion is crucial for writing robust, bug-free applications. While coercion can be useful, relying on explicit conversion improves code readability and predictability.
📁 Supplementary Resources
MDN: Type Conversion
JavaScript Equality Table: https://dorey.github.io/JavaScript-Equality-Table/
JS Visualizer: https://www.jsv9000.app/
No comments:
Post a Comment