5. Type Conversion & Type Coercion Flashcards
In How many types JavaScript can convert ?
2-3 Types
- Number to a string to a Boolean
But we cannot convert to undefined or NaN ( NaN - Not a Number ).
Example of Type Conversion
String to a Number ( Reveal Answer )
const inputYear = '1991'; console.log(Number(inputYear) + 25);
In the above example we have converted string(1991) to a number
Examples of Type Coercion
Reval Answer
console.log(‘2’ + ‘2’)
Output will be 22
Type coercion will only work in Operator like ( -, *, /, **)
Like
console.log(‘5’ - ‘3’)
Output will be 2
console.log(‘2’ + ‘2’)
Output will be 22
Type coercion will only work in Operator like ( -, *, /, **)
Like
console.log(‘5’ - ‘3’)
Output will be 2
Coding Challenge :-
LECTURE: Type Conversion and Coercion 1. Predict the result of these 5 operations without executing them: '9' - '5'; '19' - '13' + '17'; '19' - '13' + 17; '123' < 57; 5 + 6 + '4' + 9 - 4 - 2; 2. Execute the operations to check if you were right
console. log(‘9’ - ‘5’); // -> 4
console. log(‘19’ - ‘13’ + ‘17’); // -> ‘617’
console. log(‘19’ - ‘13’ + 17); // -> 23
console. log(‘123’ < 57); // -> false
console. log(5 + 6 + ‘4’ + 9 - 4 - 2); // -> 1143