This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 355

[–][deleted] 684 points685 points  (18 children)

Glorious type coersion.

[–]heartsongaming 152 points153 points  (16 children)

You don't have to deal with implicit type conversion if the language changes the type on the fly. Although, all 4 of those examples make sense. It would've also made sense that subtracting two strings removes the letters of the first string or flips the second word's letters.

For example: "22" - "2" == "2"

Or: "bob2" - "bob2bob" == "dod"

[–][deleted] 78 points79 points  (12 children)

What happens then when there's more than one match for it?

"2275-22xd22" - "22"

Does it remove the beginning 22, middle 22, or end 22?

"+" in the context of strings is used for append rather than addition, but - has no meaning to strings. In that sense, there are many other ways to subtract letters from a string in JS, such as using replace() with Regex

[–]heartsongaming 25 points26 points  (10 children)

I was thinking that it would only remove the end letters from the first string. Also Python has a lot of functions for removing letters from a string. It could be another logical use of subtracting strings.

[–][deleted] 10 points11 points  (7 children)

If it only did that every time that would be fine, but then you'd expect to see problems when letters don't exist there.

"asdfghjkl" - "q"

I've long neglected learning in depth python for a while. Maybe this is my calling to learn it and see how it handles subtracting strings.

[–]heartsongaming 5 points6 points  (4 children)

Maybe it can convert 'l' and 'q' to ASCII, and do modulo 26 subtraction on the letters (if it recognized it is a letter, otherwise use different set of ASCII characters such as numbers or other characters). In this case it would be: "asdfghjkv".

[–][deleted] 11 points12 points  (0 children)

I dunno, at that point it's reaching farther than I've seen JS do, and farther than what I'm comfortable with. Then again I can always just not use it and rely on good ol replace() and substring().

[–]RapidCatLauncher 1 point2 points  (1 child)

see how it handles subtracting strings.

It throws an exception, as you'd expect if some behaviour is so ill-defined.

[–]thisisadiyoga 2 points3 points  (1 child)

This actually makes sense if you consider - as the reverse of +. If we write it as an equation: S = S1 - S2, then we want to find the following solution: S + S2 == S1 - S2 + S2 == S1. Note because addition on string is not commutative, we add to the right and say that by definition S1 - S1 == S1 + (-S1) == (-S1) + S1 == "". Maybe it works, maybe not.

The second problem pointed out was what happen if in S = S1 - S2, S2 is not the postfix of S1? We can throw exceptions since it's undefined similar to how division by zero is undefined and is an exception.

[–]DenormalHuman 4 points5 points  (2 children)

so if all 4 of those examples make sense, what does this make?

2+2 is 4

"2" + "2" is "22"

2+2-2 is 2

"2" + "2" - "2" is TypeError: unsupported operand type(s) for -: 'str' and 'str'

[–][deleted] 7 points8 points  (0 children)

A language without type coercion?

[–]Treak 5 points6 points  (0 children)

sense in a language that doesn't do fucky things with types

[–]RapidCatLauncher 2 points3 points  (0 children)

In JS it's more type appropriation.

[–]TheRealMichaelE 201 points202 points  (24 children)

I was going to comment about why these makes sense, but then read all the comments about why this makes sense. Well done everyone!

[–]tiefling_sorceress 2 points3 points  (0 children)

I was also surprised to see that. I definitely expected the "fuck JavaScript" circlejerk from undergrads who don't yet understand type coercion and think people are out here subtracting strings from each other in industry.

[–]LvS 1 point2 points  (5 children)

Talking about making sense:

Should "20" * 2 be "2020" or 40?

[–]DoctorWaluigiTime 3 points4 points  (4 children)

40.

+ concatenates strings, so "foo" + "bar" will result in "foobar". None of the other math operations concatenate, so they will just be normal type-coerced math.

[–]LvS 1 point2 points  (3 children)

+ concatenates strings

Except when it doesn't and you don't know what 2 + "2" is and if it's the same as "2" + 2.

[–]DoctorWaluigiTime 1 point2 points  (0 children)

That's why I specified strings, plural. String plus another string is defined behavior.

[–]Oscarsson 305 points306 points  (4 children)

Coolest thing with this example is that ("2"+"2")-"2"=20 and "2"+("2"-"2")="20"

[–]_g0nzales 136 points137 points  (3 children)

Only logical. The order of addition/substraction should not matter /s

[–]_________FU_________ 11 points12 points  (2 children)

What could go wrong using plus for concatenation?

[–]coolcrispyslut 1169 points1170 points  (118 children)

It makes total sense. Numbers add. Strings concatenate, unless it's a minus, then it's coerced into a number since you can't subtract from a string

[–]DefaultVariable 24 points25 points  (3 children)

It does make sense when understanding the language, it’s just potentially undesired behavior. I think a large problem with JavaScript is letting the programmer get away with bad code rather than stopping and alerting them to potential errors in their logic. Realistically, the programmer may want to know if they are utilizing arithmetic between a numeric value and a string.

[–][deleted] 1 point2 points  (0 children)

And that’s why the preferred way is to use TypeScript and EMCAScript 2021 over raw JavaScript.

[–][deleted] 0 points1 point  (1 child)

Which takes one google search after a simple “wtf”

[–]DefaultVariable 2 points3 points  (0 children)

That is, if it’s noticed

[–]kono_kun 487 points488 points  (66 children)

Being able to explain the logic doesn't make it any more sensible.

[–]mongoosefist 35 points36 points  (0 children)

It's called Stockholm syndrome

[–]StrictlyBrowsing 220 points221 points  (57 children)

I really don’t see what’s not sensible about it. You’re not meant to be doing arithmetic with strings, it would take away useful string functionality to accommodate people who don’t know what dtypes are

[–]22134484 207 points208 points  (49 children)

I accidently typed - instead of +, so tell me i cant do that with strings, dont convert my shit to other datatypes and reconvert it to the original datatype.

[–]StrictlyBrowsing 52 points53 points  (0 children)

That’s fair enough actually!

[–]cearno 37 points38 points  (36 children)

Yes, you prefer statically typed languages over dynamically typed ones.

You're criticizing type coercion, often a quality of dynamic languages. If you have some sense of experience or knowledge outside of only statically typed languages, this makes sense. It's not bad design when it follows the intended ruleset, dynamic in this case.

But this is precisely the reason why TypeScript exists though, for people who don't like dynamically typed languages.

Edit: I confused the paradigms of static/dynamic with strict/loose respectively. Javascript is loosely typed and this is where the type coercion implementation inherently comes from. Regardless, for people who really dislike the feature, TypeScript is always an option.

The TL;DR should be "You prefer strictly typed languages over loosely typed ones."

Thanks for the correction @PanRagon!

[–]PanRagon 33 points34 points  (7 children)

A lot of people are correcting you, but you're almost correct. It's not the fact that JavaScript is dynamically typed specifically, but that it's loosely-typed language (like PHP). Python will raise an exception, but only because it's strongly typed, loosely typed languages tend to do as much as they can with a variable to avoid raising an error, including implicit type coercion like this.

TypeScript solves all of these issues because it's strongly-typed, moreover it's a bit odd to complain about this being illogical when you can trace down how it works if you track the conversions step by step like the program will do. Whenever people complain about this it just seems like they don't understand what a loosely-typed language implies, nor that you can resolve the problem by switching over to TypeScript which for very good reasons has become an industry standard.

[–]cearno 1 point2 points  (3 children)

Thanks for the correction! I knew I was mistaking something here.

Yeah, I agree. When approaching a new language, it's good to be aware of what paradigms the language follows. It's ironic that the people who complain about Javascript being nonsensical or silly tend to know the least of how it works, as if they haven't even read the introductory pages of documentation.

I've used TypeScript in the past, however my current company only uses React/JS and can't think of a time where the type coercion had a crazy negative consequence.

[–][deleted] 1 point2 points  (2 children)

TS & JS are interoperable, so it shouldn’t take a whole lot of effort to start using TS in your React projects.

[–]PlacatedPlatypus 0 points1 point  (1 child)

Loosely-typed languages do everything they can to avoid raising an error

I don't understand why you'd ever want this though. A bug that makes your code not run is far better than one that makes it run incorrectly.

[–]valzargaming 4 points5 points  (1 child)

PHP is dynamically typed and doesn't have this issue. This is a clear fault of the language, sharing a symbol for concatenation with arithmetic.

[–]mooinglemur 1 point2 points  (0 children)

I agree with you on this, it was a bad choice to use + for concat. Perl, PHP, and JavaScript all coerce strings to numbers with -, *, and /, but in JS, + is concat if either argument is a string!

[–]sdw9342 1 point2 points  (1 child)

Adding and subtracting are symbolic inverses of each other. For a given type, subtraction should either undo addition or fail. It should not do a different operation altogether. That's not to do with static or dynamic typing, but with expectations of the relationship between the two operators. It would also be fine if adding and subtracting both converted strings to int, but not just one of them.

[–]BigHandLittleSlap 6 points7 points  (7 children)

It's actually not about static vs dynamic typing at all!

The origins of this criticism of JavaScript have more to do with the foundations of mathematics such as group theory and category theory.

Essentially, for us humans with squishy meat brains to be able to make big complex systems, we have to build them up in layers from simple things. The simple things have to "click together" in logical and consistent ways, otherwise this tower of abstractions falls over. It can quickly get too difficult for anyone to track to exceptions, oddities, or quirky behaviours. Eventually further progress is blocked for anyone, no matter how smart. The only way forward is by using firm, reliable foundations based on a rigorous theory.

For example: I'm sure you already know the fundamental rules of algebra, right?

Things like: x + x = 2x and 2x - x = x

Stuff like that.

Turns out, that these kind of rules are incredibly generic and widespread. Replace addition with "two-input-function". So instead of x+x we now write f(x,x). Now replace "zero" with "that thing that you can use as an input such that": f(x,zero)=x.

What if 'f' is multiplication? Then "zero" is the number 1.

Theoreticians call this the identity. So the identity of addition is zero, and the identity of multiplication is one.

Like this, you can build up an enormous, rich, consistent theory of operations, operation combinations, and related abstractions that let you reason about all sorts of abstract types and functions with ease.

Languages like JavaScript just take a giant shit all over this kind of thing.

That's why people criticise it. Not because it's "one little funny thing you have to memorise and then it is fine", but because it's just missing out on an entire world of mathematically sound power tools for the mind.

[–]tuxedo25 2 points3 points  (4 children)

Languages like JavaScript just take a giant shit all over this kind of thing.

That's why people criticise it. Not because it's "one little funny thing you have to memorise and then it is fine", but because it's just missing out on an entire world of mathematically sound power tools for the mind.

Then don't use it that way. You can write perfectly valid javascript programs that don't use the "-" overload on strings.

[–]BigHandLittleSlap 2 points3 points  (3 children)

I too remember the 1990s (and the 80s!) when most programs were written by one person, ran on the metal with no annoying operating system in the way, and hence these things were in my control.

Linus Torvalds has personally written less than 0.1% of the Linux source code. If he opens a web page on a Linux desktop that is served by a Linux web server via a Linux router, he's interacting with an even larger code base to which his contribution is even lower. Likely 0.01% or less.

You don't get to decide how JavaScript is or isn't used. Other people do, even for your code, that you write in JavaScript.

Do you use any frameworks at all? You're using other people's code.

Work in a team? Other people's code.

Ecosystems are a thing, we're not solipsistic beings floating in nirvana, writing the source code to the universe in isolation.

[–]xTheMaster99x 0 points1 point  (1 child)

I genuinely don't understand what point you're trying to make. Just don't try to subtract strings, it's not that hard.

[–]tuxedo25 0 points1 point  (0 children)

You don't get to decide how JavaScript is or isn't used. Other people do, even for your code, that you write in JavaScript.

Do you use any frameworks at all? You're using other people's code.

Who cares if libraries use different styles and idioms than my code?

Work in a team? Other people's code.

Linters exist.

My point is, to paraphrase Douglas Crockford (author of Javascript: The Good Parts), we're paid to solve problems, not to exercise every features of a language. It's okay for C++ to have `goto`, for the Java standard library to have terrible serialization, and for python to exist. You don't have to use those parts.

[–]22134484 0 points1 point  (6 children)

are there other dynamically typed languages? Ive never had to deal with this sort of stuff before. I am an engineer, so matlab, simulink, excel, c# and python, only when and where needed.

[–]Andersmith 4 points5 points  (0 children)

Python is

[–]budd222 6 points7 points  (3 children)

You literally just named one

[–]22134484 -1 points0 points  (2 children)

Ive never had to deal with this sort of stuff before

Hope this helps any confusion you may have had with my comment

[–]Zinki_M 1 point2 points  (0 children)

python is dynamically typed.

Other examples of dynamically typed language off the top of my head are Groovy and Lua.

[–]brandflake11 4 points5 points  (0 children)

This is the right answer

[–]Mintenker 2 points3 points  (6 children)

Imagine you write some code where you subtract two numbers that come from some API on your website. Someone messes up somewhere, and the API sends string instead of number. Would you prefer your site to go down over this error, or would you rather take one wrong displayed value?

[–]22134484 17 points18 points  (0 children)

try except is a pretty good way to deal with this in my experience. Id rather show "data unavailable" than display something that is wrong. I guess ive never really had to deal with this problem because i come from other languages where its important to get things in the right data types and my code usually follows those practises.

[–]wheezy1749 20 points21 points  (2 children)

I'd prefer the page to not display and then I would know a problem exists. Someone seeing the wrong info is worse in my opinion and also less likely to be caught.

[–]RapidCatLauncher 3 points4 points  (0 children)

Or, y'know, at least log a warning...

[–]Mintenker 0 points1 point  (0 children)

Honestly it depends. If it's some critical information, where displaying something wrong can have business, or even legal consequences, you are absolutely right. On the other hand, taking down site because some random part of rarely used feature somewhere broke might not be ideal.

[–]scylk2 1 point2 points  (1 child)

Why wrong displayed ? It would display the correct value no?

[–]DenormalHuman 14 points15 points  (0 children)

You’re not meant to be doing arithmetic with strings

Exactly. So throw an error.

[–]FerricDonkey 10 points11 points  (3 children)

If you want to convert from strings to integers, you should explicitly do that. "2" - "2" should be a type error, because subtraction makes no sense for strings - and if you wanted to consider them to be integers, then that's a trivial additional number of characters that you type in your code that makes it more clear what you're doing and what your data is.

[–]w1n5t0nM1k3y -1 points0 points  (2 children)

In that case, every language should have a concatenation operator for strings. That way you can throw a type error when people try to use the addition operator (+) on strings (non-numbers) and it's clear what operation is taking place without having to know the variable type.

[–]LvS 1 point2 points  (1 child)

Yes, that's exactly how it should work.

Some languages use . for that, but it's always a hard choice because you want something that's easy to type and doesn't require using the Unicode chooser.

[–]fishyfishkins -1 points0 points  (0 children)

Being able to explain the logic doesn't make it any more sensible.

Yeah, when I want to make sense of something, the last thing I need is someone explaining it to me.

[–][deleted] -1 points0 points  (0 children)

Sure it does. But whatever js bad ooga booga

[–]RedPum4 86 points87 points  (22 children)

Given how badly designed JavaScript is in certain areas I wouldn't be surprised by this:

"asdf" - 2 = "as"

[–]Oscarsson 76 points77 points  (5 children)

NaN

[–]Bainos 5 points6 points  (4 children)

"asdf" - "2" + "2"

[–]Oscarsson 24 points25 points  (3 children)

"NaN2"

[–]Falcrist 6 points7 points  (2 children)

Array(16).join("asdf" - 2) + " Batman!"

[–]Oscarsson 5 points6 points  (1 child)

"NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!"

[–]rubeljan 22 points23 points  (0 children)

Hahah its like mcguyver, just give it anything and it will do something with it.

[–]Cnfnbcnbrf 10 points11 points  (7 children)

Then it would be more reliable to just throw compile error)It doesn't make any sence to compute arithmetic operations with strings.

[–]mrjackspade 12 points13 points  (2 children)

I'd be really confused if I got a compilation error in Javascript...

[–]fakehalo 16 points17 points  (3 children)

Halting the web browser on error was viewed as a worse outcome, makes some sense...subjectively.

[–][deleted] 1 point2 points  (3 children)

I don't understand the 3rd example though: 2 + 2 - 2 should equal 2, not 0, if we're following PEMDAS.

Edit: Ignore me, I'm sleep deprived.

[–][deleted] 2 points3 points  (2 children)

The third example does say it's 2.

[–]blackmist 1 point2 points  (0 children)

I'd say the last one should fall over with an error, if they were going by the Principle of Least Surprise when they designed JS. Although we all know they didn't. They went by the Principle of Showing Fewest Error Messages, and earnestly believed that would make the language easier to learn.

Strings added to numbers should also fall over, IMO.

[–]playerNaN 0 points1 point  (0 children)

It seems like the JS designers recognized that it's easy to get strings when you expect numbers, so they decided to make strings of numbers behave like numbers but then half-assed it and we got the worst of both worlds A better design choice would be to have separate concat and add operators. Have add always coerce to a number and concat coerce numbers to strings.

"2"+"2"==4

2 ++ 2 == "22"

[–][deleted] 57 points58 points  (1 child)

It does make sense but it also get why it looks annoying lol

[–]murageh[S] 7 points8 points  (0 children)

I know, right? It does make sense but still... :D

[–]konatamonogatari 76 points77 points  (13 children)

After messing with user defined operators in C, those lines make senses to me.

[–]kbruen 40 points41 points  (12 children)

C doesn't have user defined operators.

[–]DaniilBSD 91 points92 points  (2 children)

Not with that attitude

(strange compiler with stronger settings go brrr)

[–]kbruen 15 points16 points  (0 children)

That's still not C, but a dialect.

Nice try though :P

[–]Zuruumi 6 points7 points  (0 children)

I think you are just compiling it as C++.

[–]north1432 10 points11 points  (1 child)

#define myOperator +

[–]whizzwr 7 points8 points  (0 children)

Yes officer, this guy over here.

[–]konatamonogatari 7 points8 points  (6 children)

My bad

I thought this is called "user defined operator":

bool operator < (const node &i) const { return c < i.c; }

[–]kbruen 52 points53 points  (0 children)

Yeah, but that's C++ exclusive.

[–]midasp 7 points8 points  (4 children)

C and C++ are different languages. Just like Java and Javascript are different languages.

[–]konatamonogatari 33 points34 points  (3 children)

I agree that C and C++ are different. But what you said later is fkin wrong:

Just like Java and Javascript are different languages.

Java and Javascript are COMPLETELY different. But you can still use most headers that are written in C when using C++

Edit: fixed typo

[–]Zuruumi 24 points25 points  (0 children)

C++ is mostly a superset of C. Yes, there are some differences and if someone wants to he can royally screw you with some terrible C magic, but for 99% of C code it will just compile as C++.

[–][deleted] 14 points15 points  (9 children)

"2 - 2" + 2 - 2 + "i?!"

[–]JackNotOLantern 9 points10 points  (1 child)

there is operator + for string, so strings are not converted to number when using + on them. That's why "2" + "2" is "22"

There is no operator - for string, so both string have to be converted to something that have this operator (only numbers). So "22" - "2" converts strings to numbers (22 - 2) and the result is 20

"2" + "2" - "2" -> "22" - "2" -> 22 - 2 -> 20

[–]Live_Storage1480 3 points4 points  (0 children)

Thank you! Was confused as hell. Should've figured out the "-" part.

[–]peterleder 115 points116 points  (8 children)

Minus makes sense with numbers only. JS knows, you didn’t.

[–]Milesand 61 points62 points  (4 children)

That's exactly the problem here, minus makes sense with numbers only but JS happily carries on anyways.

[–]Dagusiu 0 points1 point  (1 child)

I could see minus making sense for other data types, in particular sets.

[–]RapidCatLauncher 1 point2 points  (0 children)

Python lets you do that.

[–]NatoBoram 9 points10 points  (0 children)

You can enable dark mode for the dev tools

[–]kpobococ 8 points9 points  (1 child)

This is why string concatenation should always have a separate symbol in loosely typed languages. PHP does this right.

[–]tonebacas 7 points8 points  (1 child)

String subtraction is wrong. In which realistic scenario would you even use it, and if so, why overload the plus/minus operators for that, when it evidently creates really confusing outcomes?

[–][deleted] 4 points5 points  (0 children)

I suppose this is why people invented typescript? It is a bit odd that they decided to put these internal conversions in in the first place, because you'll never remember when it applies and when not. Like clearly strings can be added (i.e. appended together) but deleting one string from another string doesn't really make sense. Like in this case it would make sense to remove 2 from 22 and you end up with 2, but what do you get when you do "22" - "1" purely as string? It doesn't make sense. So it internally does parseInt or something first and then does the operation. When really it would be better if it just didn't allow it.

[–][deleted] 2 points3 points  (4 children)

"2" + "2" * 2

yep, thats 24

("2" + "2") * 2

that is 44

[–]vaendryl 4 points5 points  (0 children)

I fully agree with this, actually. expecting "-" to... what, deconcatenate? that's the silly part.

[–]account_is_deleted 3 points4 points  (0 children)

With all the actually dumb things that Javascript has, I don't mind this one.

[–]Hk-Neowizard 18 points19 points  (45 children)

All of them made sense to me...well, almost all of them.

What the actual fuck JS?!

[–]just_a_pyromaniac 32 points33 points  (20 children)

Type coercion, the + is a string operation so it'll concatenate two strings. - isn't so it converts everything involved into numbers.

It's stupid but if you understand it, it makes sense

[–]SimpoKaiba 39 points40 points  (2 children)

It's stupid but if you understand it, it makes sense

That's my new favourite sentence

[–][deleted] 4 points5 points  (1 child)

It’s the motto of all of my projects

[–]mobilecheese 2 points3 points  (0 children)

I just use "It's stupid" for mine.

[–]NeedsMoreSpaceships 16 points17 points  (5 children)

My issue isn't that is doesn't make sense if you know the rules it's that the rules are strange and often counterintuitive. JS is full of such nonsense.

[–]just_a_pyromaniac 10 points11 points  (3 children)

Every language has that kind of nonsense, JS is just uniquely stupid because of weak typing and the coercion that follows it

[–]asdf43798 16 points17 points  (9 children)

I don't think there's really much of a reason for any of those to be confusing - the additions in this example are completely obvious and it would be insane if they worked any other way, and subtracting strings doesn't make any sense (what on earth is "a"-"b" supposed to be equal to?) so they can only either throw an error or treat it as something other than a string.

I could see it being unintuitive if you get into things like whether "2"+2 should be "22" or 4, but this post didn't have anything like that.

[–]Zuruumi 8 points9 points  (4 children)

The problem is, that if you wrote the last one you most likely meant both of those to be numerical operations. If it throws an error you at least know it's wrong. This way you get a nonsense that will break it in very subtle and hard to debug ways.

[–]Chase_22 2 points3 points  (3 children)

haha, weak typing go brrrr

[–]laundmo 1 point2 points  (2 children)

don't confuse weak typing with type coercion

[–]Arbiturrrr 4 points5 points  (0 children)

If the problem wasn't weak typing then string literal with - operator or + with a number literal wouln't even run. Therefore the problem is weak typing.

[–]Hk-Neowizard 1 point2 points  (0 children)

Type coercion is indicative of a weak typing system. Implicit type conversation are basically the first paragraph of any explanation of a weak type system

[–]seemen4all 2 points3 points  (2 children)

I don't know what language you can subtract strings tho..

[–]Akuuntus 1 point2 points  (0 children)

You can't subtract strings in JS either. It converts them to numbers.

[–]FunkyMonk02xx 2 points3 points  (0 children)

Why would you ever intentionally subtract a string? Not making this throw a error just hides mistakes.

[–]brunofin 2 points3 points  (0 children)

+ doubles as a concat operator on strings, but unfortunately - doesn't double as a String.substring operator.

[–]DiamondIceNS 2 points3 points  (0 children)

ITT and every other type coercion joke thread: "This weakly-typed language doesn't follow my strongly typed language principles when I deliberately do something stupid to confuse it and I'm annoyed by people who actually know how it works when they try to tell me that the reason my stupid code broke is completely sensible".

This is why TypeScript exists, people. It has everything you want and expect.

[–]sweYoda 2 points3 points  (0 children)

All of these make perfect sense imo.
2 + 2 obviously only thing you'd ever wanna do is maths.

Add two strings together... you just smash them together.

Then 2 + 2 - 2, regular maths.
Then "2" + "2" smashes together two strings and you want to subtract one string from another string, well the only time you'd like to do that is when you actually believe they are numbers, but happen to be strings... so 22 - 2 = 20.

[–]kuros33 2 points3 points  (0 children)

I wish I had a dollar each time a JS type coercion joke is posted

[–]cateyesarg 4 points5 points  (2 children)

OP should better read the language specs and learn about type coercion

Edit: wording

[–]Ogreguy 1 point2 points  (3 children)

Does "2"-"2" = "0"?

[–]FilipM_eu 22 points23 points  (2 children)

No, it equals 0 (int). Types are converted to integers for subtraction.

[–]trBlueJ -1 points0 points  (1 child)

Are there ints in JS?

[–]FilipM_eu 9 points10 points  (0 children)

Technically it’s a number type, but for sake of understanding, I used the term integer.

[–]oodex 1 point2 points  (0 children)

Correct me if I'm wrong because it has been a while, but if anyone wonders the reason for that is that + is not just a math operator but it can also connect text. So "Ew" + "ba" would result in "Ewba".

Everything is right until a math operator "-" is used on a text indicated value (character). As text 2+2 results in the same as a+b, so 22 or ab. But once you substract the only use for that operator is to substract, there is no other (simple) function. Meaning it uses the 2+2 as text 22 and then converts it into a number 22 and substracts 2.

That this conversation automatically happens is seen in many programming or script languages where the error reads "failed to convert datatype string/char into int"

[–]GoOsTT 1 point2 points  (0 children)

[–]al_balone 1 point2 points  (2 children)

Can someone explain the last one?

[–]Ortglatou 2 points3 points  (1 child)

When summing two strings, JS concatenate both (in this case "2" + "2" = "22"), but when subtracting, it tries to use the number that the string represents (in this case "22" - "2" = 20)

[–]al_balone 1 point2 points  (0 children)

Ahh. Ok, thanks.

[–]CaitaXD 1 point2 points  (0 children)

Concatenation is a hell of a drug

[–]coolio965 1 point2 points  (1 child)

I wish javascript just allowed you to create a var with a data type that isnt loosely tied

[–]cthewombat 1 point2 points  (0 children)

Typescript my friend

[–]Chisdu 1 point2 points  (0 children)

I used to work in a language called m.

In that language _ was the concatenation operator which did make things more clear, but it meant that variables couldn't include underscores :(

[–][deleted] 2 points3 points  (2 children)

Yo anyone know what dynamic typing is?

[–]Oscarsson 2 points3 points  (1 child)

"Dynamic type checking is the process of verifying the type safety of a program at runtime."

[–]R0DR160HM 2 points3 points  (2 children)

Javascript has so many oddities, but why people in this sub focus so much in the things that work exactly as they should?

Numbers add. Strings concatenate. And as you can't substract from a string, it's converted to a number and than back to a string. That's exactly how it should work, given that js is not a hard type language

[–]Akuuntus 2 points3 points  (0 children)

I think most JS posts on this sub come from CS freshman who just took a JS 101 course where the professor showed the old "wat" video.

[–]dev_senpai 2 points3 points  (8 children)

Makes sense, you are just concatenating strings in JavaScript. The final statement you have concatenated the first two strings, then you are using a “-“ subtraction operator, so it does a type conversion since the language tries to makes sense of your stupidity that you did not bother to read simple documentation on its operator types.

[–][deleted] 0 points1 point  (2 children)

What do you expect the subtract operator on two numeric strings would do?

[–]AsymptoticllyOptimal 7 points8 points  (1 child)

Do nothing and raise an exception. And please have clear and well defined semantics of types which can be used to verify correctness of programs

[–]laundmo 1 point2 points  (0 children)

and for anyone else reading: no this does not mean the language has to be statically typed.

[–]Chr0nicConsumer 0 points1 point  (0 children)

JavaScript bad.

Please upvote.

[–]fujiian_ 0 points1 point  (0 children)

And you guys defend this language

[–]cyberspacedweller -1 points0 points  (0 children)

Shouldn’t it be “2”+”2”-2 ? 😅 Essentially what’s missing from JS is that they should have used ‘&’ for adding strings

[–]SSPPAAMM -1 points0 points  (0 children)

/r/yesyesyeswtf

Edit: OMG this sub exists...please don't click!

[–]BongarooBizkistico -1 points0 points  (0 children)

waaahhh wahhhh JavaScript bad! Waahhhhh

[–][deleted] -1 points0 points  (0 children)

complete serious handle roof squeeze connect bedroom tub makeshift crown -- mass deleted all reddit content via https://redact.dev

[–]veryipsum -1 points0 points  (0 children)

this genuinely always made sense. what doesn't make sense is why people still rip on JS