Last time I've used Javascript was about 7 or 8 years ago - But:
The + operator in Javascript (as in many other languages) have two different Jobs: It acts as an addition operator, and as a string concatenation operator.
Since Javascript is a weakly typed language, implicit conversions are everywhere.
When the Javascript engine sees "11" + 1 it implicitly converts the numeric 1 to a string, therefor the + here acts as a string concatenation operator, and the result is "111", which is a string, not a number.
The - operator, however, has no effect with strings. Try "asdf" - "a" and see what happens.
Therefor, in this case, the Javascript engine implicitly converts the string "11" to a number, and the result 10, which is a number, not a string.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
I've been a professional C, Perl, PHP and Python developer.
I'm an ex-sysadmin from the late 20th century.
These days I do more Javascript and CSS and whatnot, and promote UX and accessibility.
Top comments (7)
Short answer: you can add strings, but you cannot subtract them, and addition is also used in numbers :D
Easy peasy. You know 😁
Good reply 😃
Last time I've used Javascript was about 7 or 8 years ago - But:
The
+
operator in Javascript (as in many other languages) have two different Jobs: It acts as an addition operator, and as a string concatenation operator.Since Javascript is a weakly typed language, implicit conversions are everywhere.
When the Javascript engine sees
"11" + 1
it implicitly converts the numeric1
to a string, therefor the+
here acts as a string concatenation operator, and the result is "111", which is a string, not a number.The
-
operator, however, has no effect with strings. Try"asdf" - "a"
and see what happens.Therefor, in this case, the Javascript engine implicitly converts the string
"11"
to a number, and the result 10, which is a number, not a string.I would say that the first is type coerced from a string and the second is 2 numbers. Perfectly normal nobody panic 😅.
Not sure I want to know.
Yes.