Ala
Ala

Reputation: 1503

Implicit conversion in Javascript

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

Answers (4)

ashish singh
ashish singh

Reputation: 1

The + operator always explicitly converts number into string if operating together with string

Basic representation:

  • N+S >> N
  • S+N >> S
  • S+S >> S
  • N+N >> N
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

Alain
Alain

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

codejockie
codejockie

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

Jonas Wilms
Jonas Wilms

Reputation: 138437

No, the unary plus operator (the second +) explicitely converts a string to a number.

Upvotes: 1

Related Questions