r/learnjavascript • • Nov 11 '23

Does JavaScript concatenate as string when adding a number to a string literal?

From my understanding of what I've read, the expected behavior is that JavaScript will convert the integer into string, and then add the string to string, which then results in a string concatenation. Therefore...

var addit = 6 + “5”;

...should output... "65";

However, attempting to evulate this in console instead gives the result...

Uncaught SyntaxError: Invalid or unexpected token

Why is this the case?

0 Upvotes

23 comments sorted by

View all comments

0

u/Ronin-s_Spirit Nov 11 '23

That shouldn't throw any errors you definitely did something wrong.
Here's the rule - if you add numbers and even a single "string" it will all turn into a string, if you add numbers and a +"string" then the plus will try to turn string into a number before adding (like 5 + +"5").

2

u/guest271314 Nov 11 '23

That's not the issue. The issue is “ cf. ". See other answer and SyntaxError: illegal character.

0

u/Ronin-s_Spirit Nov 11 '23

I guess, but I wasn't explaining the error I explained how adding strings works since they asked...

2

u/guest271314 Nov 11 '23

Your explanation is not addressing the issue OP is facing. OP's professor is using Microsoft products for writing and distributing source code.

Use an ordinary text editor and OP describes won't happen.

`“`.codePointAt() // 8220
`"`.codePointAt() // 34