DEV Community

Discussion on: Meme Monday

Collapse
 
j471n profile image
Jatin Sharma

No one.

JavaScript:

Image description

Collapse
 
cmgustin profile image
Chris Gustin

I know I’m being the guy that overexplains the joke, but in case anyone new to JS sees this and is curious about what’s going on:
The + operator in JS can either be addition or string concatenation. JS decides based off of the types you’re trying to add together. JS may also change the type of a variable on the fly if it thinks what you’re trying to do doesn’t make sense.

  • Line 1, two numbers so the “+” sign is addition
  • Line 2, two strings so the “+” sign concatenates them (same as “Hello “ + “world” would result in “Hello world”)
  • Line 3, first variable is a string so the “+” concatenates. JS coerces the second variable, a number, to a string so the concatenation will work
  • Line 4, first variable is a number, and the extra “+” sign converts the second variable, a string, to a number, so the output is addition. In JS, you can put a “+” before a variable to convert it to a number, like “const num = +my_var;”
  • Line 5, all variables are numbers so the “+” is for addition
  • Line 6, all three variables are strings, so the “+” concatenates the first two. However, the “-“ operator is always used for subtraction so JS coerces the concatenated “33” and the last “3” string to numbers in order to complete the subtraction operation, giving 30

These quirks can be annoying, especially starting out, but as you learn the language and understand how the dynamic typing system works, it gets easier. The important thing is to always know the types of your variables and make sure they’re explicitly typed (e.g. numbers are numbers and not strings that look like numbers) rather than relying on JS’ built-in type coercion, which can cause unexpected bugs.