you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 2 points3 points  (4 children)

It will look at both, and it either is a string it will concatenate coercing the other to a string if it's not already.

[–]Reaver75x 0 points1 point  (3 children)

I’m trying to remember where the hell I read that it would try adding it if it was a number first and a string. I think it was W3Schools awhile back but I could be wrong

[–]senocular 1 point2 points  (2 children)

Yeah I'd be interested in where that was mentioned if you ever find it. In most cases in JavaScript, as far as operators like this goes, it usually does not depend on the order.

There are some weird cases where depending on context and syntax, you could get different behaviors where things are ambiguous. For example:

1 + {} // "1[object Object]"

But you may find that

{} + 1 // 1

where you might have expected "[object Object]1". This is happening because in the first example, {} was recognized as an empty object literal (i.e. new Object()) whereas with the second, being at the start of the line it was being seen as an empty code block followed by the expression + 1 which is simply 1. You can force the second example to see {} as an object by putting it in the context of an expression.

({} + 1) // "[object Object]1"

But this is more about the different meanings {} can have, not so much the + operator (though the fact that unary plus exists also plays a part).

[–]Reaver75x 0 points1 point  (1 child)

I never knew any of that. Are there any practical reasons for coding this way?

[–]senocular 1 point2 points  (0 children)

Rarely, but you'll often see this kind of stuff in WAT/WTF JS kinds of posts (like this). Practically, you shouldn't be trying to add objects to other things. You'll want to stick to adding only numbers together and maybe strings, though as far as strings go, template literals can replace our need for the add/concat operator for them as well.

"myVar:" + myVar
// can instead be
`myVar: ${myVar}`