careerbydoing
← Web development

Web development

When JavaScript guesses what you meant

About 3 min if you have seen this material before, 10 min or so if it is new to you.

Background
Python raises a TypeError if you add a string to a number. JavaScript instead performs JavaScript's habit of silently converting between types when an operator gets operands it did not expect.: it silently converts one operand and carries on. Coming from Python, this is the single most surprising thing about the language, because the program does not stop. It produces a plausible-looking wrong answer. What makes it worse is that the rule is not uniform across operators. + is overloaded: it means both numeric addition and string concatenation, so if either side is a string, JavaScript concatenates. Every other arithmetic operator has no string meaning at all, so it converts both sides to numbers instead.
What do these two lines print? Give both outputs separated by a space.
console.log("2" + 2);
console.log("2" - 2);

Past 30 min on this? That usually means a missing prerequisite rather than a lack of effort — worth reading up before pushing further, starting with Type coercion (MDN).

Want to go deeper?