Reputation: 1503
Why are the following results different using JavaScript?
console.log(1 + + "2"); // => 3
console.log(1 + "2"); // => 12
Is there an implicit conversion in JavaScript?
Upvotes: 1
Views: 3689
Reputation: 1
The +
operator always explicitly converts number
into string
if operating together with string
Basic representation:
console.log("1"+1) // 11
console.log(1+"1") // 11
console.log(1+1) // 2
console.log("1"+"2") // 12
The -
operator always explicitly converts string
into number
if operating together with number
console.log("1"-1) // 0
console.log(1-1) // 0
console.log("1"-"1") // 0
console.log(1-"1") // 0
Unary +
/-
operators always explicitly convert string
into number
console.log(11+ +"1") //12
console.log(11+ -"1") //10
Upvotes: 0
Reputation: 31
Try:
console.log(Number(1) + Number(+"2"));
console.log(Number(1) + Number("2"));
More info about type casting or conversion at https://www.w3schools.com/js/js_type_conversion.asp
Upvotes: 1
Reputation: 10872
When you use the unary +
operator on a string, it converts it to a number but this was done explicitly as you appended +
to a string. That explains why you have 1 + +"2"
being 3.
For the other case you are simply doing string concatenation.
JavaScript has the concept of automatic type conversion which is done implicitly when you perform some operation.
And to answer your question:
Yes, there is implicit conversion in JavaScript.
Upvotes: 1
Reputation: 138437
No, the unary plus operator (the second +
) explicitely converts a string to a number.
Upvotes: 1