Implicit conversion

console.log(“foo” + + “bar”)
result = fooNaN

Please explain the result


“foo” + + “bar”
= “foo” + (+ “bar”)
= “foo” + NaN
= fooNaN

Unary + operator has higher precedence over binary + operator.
So + “bar” expression will be executed first. Unary + triggers numeric conversion for string “bar”. As the string does not represent a valid number so the result is NaN.
Hence in the end “foo” + NaN is evaluated.

Few Cases-

  1. console.log(‘foo’ + ’ ’ + ‘bar’)
    result= foo bar
    In this case you have to add space between both the strings.
  2. console.log(‘foo’ + ‘bar’)
    result= foobar

There are many methods for type conversion like String(anything)=“Anything” or Number (“1.23”) =1.23, similarly + operator has so many functionalities if it is used with “a”+“b” =“ab”,in string used for concatenation ,2+3=5 just an additional operator,now it is also used for converting string to number if the passed value is Numeric data inside double const a=“123”,console.log(+a),output=123,so now the precedence of this type conversion is higher than concatnation operator,so +“bar”=NaN,so “foo”+NaN=“fooNaN”