# Implicit Coercion
# What is it
Javascript attempting to coerce an unexpected value to the expected value.But it should be avoided.
3 * "3"; //9 1 + "2" + 1; //"121" true + true; //2 10 - true; //9 const foo = { valueOf: () => 2 }; 3 + foo; // 5 4 * foo; // 8 const bar = { toString: () => " promise is a boy :)" }; 1 + bar; // "1 promise is a boy :)" 4 * []; // 0 4 * [2]; // 8 4 + [2]; // "42" 4 + [1, 2]; // "41,2" 4 * [1, 2]; // NaN "string" ? 4 : 1; // 4 undefined ? 4 : 1; // 1
Copied!
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Non-numeric value in numeric expressions
# Strings
Whenever you pass a string as an operand in a numeric expression involving either of these operators: -
, *
, /
, %
, the number's conversion process is similar to calling the in-built Number function on the value.but a string containing a non-numeric character returns NaN
.
3 * "3"; // 3 * 3 3 * Number("3"); // 3 * 3 Number("1,"); // NaN Number("1+1"); // NaN Number("1a"); // NaN Number("one"); // NaN Number("text"); // NaN
Copied!
2
3
4
5
6
7
8
+
performs different functions from other operators:
// concatenation 1 + "2"; // "12" 1 + "js"; // "1js" // addition 1 + 2; // 3 1 + 2 + 1; // 4 //addition, then concatenation 1 + 2 + "1"( // "31" 1 + 2 ) + "1"; // "31" //concatenation all through 1 + "2" + 1( // "121" 1 + "2" ) + 1; // "121"
Copied!
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Objects
Most Javascript Object conversions usually result in [object Object], For example
"name" + {}; // "name[object Object]
Copied!
The return value of the toString method is used for such operations as string concatenation and mathematical expressions.
const foo = {}; foo.toString(); // [object Object]
Copied!
2
# Array objects
Arrays will calling toString()
when involves numeric expression:
[1, 2, 3].toString(); // "1,2,3" "me" + [1, 2, 3]; // "me" + [1,2,3].toString() = "me1,2,3" 4 + [1, 2, 3]; // "41,2,3" 4 * [1, 2, 3]; // NaN
Copied!
2
3
4
5
# toString & valueOf
When both the toString
and valueOf
methods are defined on an Object, Javascript uses the valueOf method instead.
const bar = { toString: () => 2, valueOf: () => 5 }; "sa" + bar; // "sa5" 3 * bar; // 15 2 + bar; // 7
Copied!
2
3
4
5
6
7
8
# Falsy and Truthy
There are a handful of values in Javascript that return falsy values, they are:
- false
- 0
- null
- undefined
- ""
- NaN
- -0
Everything else is truthy