Reputation: 337
I'm reading a JavaScript tutorial on implicit and explicit coercion.
What happens in the background with respect to implicit coercion?
var a = "42";
var b = a * 1; //this is implicitly coerced to 42 -- the number
Does implicit coercion ALWAYS coerce to a number? What if we wanted to do something a per the below Python example.
I'm getting confused because other languages such as Python would give you a result as per below.
a = "3";
b = 9;
print a * b; //This would print 333333333 -- the string
Upvotes: 4
Views: 654
Reputation: 18515
I will leave this here for your convenience to draw some conclusions as far as implicit coercion goes:
true + false // 1
12 / "6" // 2
"number" + 15 + 3 // 'number153'
15 + 3 + "number" // '18number'
[1] > null // true
"foo" + + "bar" // 'fooNaN'
'true' == true // false
false == 'false' // false
null == '' // false
!!"false" == !!"true" // true
['x'] == 'x' // true
[] + null + 1 // 'null1'
[1,2,3] == [1,2,3] // false
{}+[]+{}+[1] // '0[object Object]1'
!+[]+[]+![] // 'truefalse'
new Date(0) - 0 // 0
new Date(0) + 0 // 'Thu Jan 01 1970 02:00:00(EET)0'
But long story short the rules are such that unless you do an explicit coercion Javascript would do one for you (hence implicit) based on the operation and the operand types involved.
You can check the JavaScript Coercion Rules table to get a full prospective.
One thing to note:
JavaScript coercions always result in one of the scalar primitive values, like string, number, or boolean. There is no coercion that results in a complex value like object or function.
Upvotes: 4