Why Does JavaScript Do This?! #001

Today we're taking a look at the following:

console.log("3" + "3" - "3")


As simple as this seems, it might be tricky. Take a minute to think about it... No cheating and running it in the console yet. What's the answer?

Let's break it down.

First we've got the string 3, plus the string 3.

"3" + "3"


In JavaScript, '+' is the addition operator as well as the concatenation operator. Since it sees that these are strings (and not numbers, since they have quotes around them), it will concatenate the two strings, giving us...

"33"


Moving on, we now have the following:

"33" - "3"


The '-' sign is ONLY a math operator and since we can't (subconcatenate?) JavaScript will try to coerce the values to numbers, which in this case is successful and gives us...

33 - 3


From there it's a simple math operation and thus when you try to console.log("3" + "3" - "3"), the result will be the number 30.

Check out the video here - https://youtube.com/shorts/lMutpIV4mtg?feature=share