What is Type coercion?
Explicit coercion / Type casting: developer intentionally converting value types
1
2
3var x = 10;
var str = x.toString();Implicit coercion / Type coercion: Type automatically converted by the JavaScript engine regardless of developer intent.
1
2
3
4
5var x = 10;
var str = x + '';
// x = Number 10, str = Sring 10Does reassignment occur when type coercion occur?
No. It only takes a moment to type when evaluating expressions.
The developer can use implicit type conversion intentionally.
Implicit type coercion
The JavaScript engine performs implicit type coercion when evaluating expressions, taking into account the context of the code.
1 | '10' + 2 // '102' |
When an implicit type coercion occurs, it automatically converts the type to one of the primitive types such as string, number, or boolean.
Coercion to String type
1 | // Number type |
Coercion to Number type
1 | // String type |
Coercion to Boolean type
When evaluating a non-boolean value with a boolean, there are only 6 values that evaluate to false.
- Falsy value
- false
- undefined
- null
- 0, -0
- NaN
- ‘’ (empty string)
- Truthy value
- non-falsy values
1 | // The following conditional statements all execute code blocks. |
Explicit type coercion
Call the wrapper object constructor used to create the Wrapper object without new
1
2String(1); // '1'
Number('1'); // 1
Using the built-in method provided by JavaScript
1
2(1).toString(); // '1'
parseInt('-1'); // -1Using implicit type coercion
1
2
31 + ''; // '1'
+ '-1'; // -1
'-1' * 1; // -1
Short-Circuit Evaluation
The logical AND operator &&
and the logical OR operator ||
return the operand that determined the logical evaluation. This is called short-circuit evaluation.
Logical OR operator
||
1
'Cat' || 'Dog' // 'Cat'
- The logical OR operator
||
returns true even if only one of the two operands evaluates to true. - The OR operator
||
returns the first operand that determines the result of the logical operation, that is, the string ‘Cat’.
- The logical OR operator
Logical AND operator
&&
1
'Cat' && 'Dog' // 'Dog'
- The AND operator
&&
returnstrue
when both operands evaluate to true. - The logical AND operator
&&
returns the second operand that determined the result of the logical operation, the string ‘Dog’.
- The AND operator
Short evaluation means that
&&
and||
return the operand that determined the logical evaluation.Used to reduce TypeErrors
1
2
3
4
5
6var elem = null;
console.log(elem.value); // TypeError: Cannot read property 'value' of null
console.log(elem && elem.value); // null
if (elem) console.log(elem.value);