The `in` operator checks for a property or field name, not values. In the case of an array, the field names are the keys. In this case the properties of the object are 0,1,2,3 - so 7 is not a property of this object.
Just because it’s an object doesn’t mean it is a hashmap is how I think about it. Though the point is that if the operation doesn’t make sense on the type of- don’t allow it. But it’s just something you have to deal with dynamically typed languages.
Because JS is designed to never crash and never error if the runtime has anything to say about it. It'll do literally anything else if at all possible, no matter how stupid the result. A site messing up is a better user experience than a site crashing or otherwise breaking your browser, after all.
(I don't agree with it either, since "reject invalid script" was also an option. But the reasoning does exist.)
Old JavaScript was a MESS, lots of horrible decisions (including this one). Modern JS maintains compatibility so we have to deal with it. of is the equivalent modern operator that behaves sanely.
I mean, most of the decisions make sense when you remember the language was only made to show popups and was purposefully designed to be non blocking and make sure HTML was never blocked by JS failures.
The fact that we use it to power smart fridges and their servers 30 years later is on us.
Also, TypeScript removes 90% of JavaScripts mind games anyways.
That's a bad philosophy. Unexpected behavior is exactly what you don't want. The program will continue into unplanned behavior. It could have any consequence. Maybe it'll move past a security check and grant an attacker access, delete your game save or transfer you money to the wrong account? Anything can happen, really.
The right philosophy is "fail fast", which is to reset to a know good state as soon as something unexpected happens.
Remember that JavaScript was designed as a browser scripting language, so it would not have done any of the critical things you just mentioned. “Fail fast” would have been “ the website is not working anymore”, and the designers decided that this was more undesirable than some strange behavior.
I’m not sure if I’d agree in the same situation, and I certainly wouldn’t in today’s JavaScript position, but I understand the tradeoff at that time.
The issue isn’t that javascript is wrong, it’s that it’s extremely misleading. A subtle difference in meaning (key membership vs value membership) with an operator that looks correct leads to a bug, and potentially even a latent one at that.
Well formulated. When I was learning JavaScript / Typescript as a backend language I face a bug with a test explicitly testing that this bug was not there.
After debugging it was a similar issue a language subtility (to a neophyte) and from this (and a few other similar examples) grew my dislike of the language.
Yes, not knowing what syntax does for the tech you're using does lead you to a place of confusion. If stuff like this trips you up for more than a couple months of using the language, then you're not really trying to learn it
It's more that the in operator is an operator for objects, not specifically arrays. Consider:
class Car {
make = "Toyota";
model = "Corolla";
wheels = 4;
}
var a = new Car();
var hasMake = "make" in a; // returns true
So the "make" property is in the Car object. It checks if the property exists on the object. Javascript is unusual in that it has a lot of object-level operators, so the same operator is used for classes as well as arrays. There's no reason why you would use in for this purpose on arrays - it's just that you can.
because arrays are objects, so much so that there's a check (Array.isArray()'s implementation) for an internal marker only applied when the array is created via [] or Array(). it's an object with a brand, in the internal representation.
the way you'd have to check before that was introduced was to check if it pretended to be an array- that is, if it had .push(), if it was an instanceofyour window's Array, or if .prototype.toString() returned "[object Array]" (though you could reassign this function too).
Slight correction: Array.isArray exists because instanceof Array can fail when passing values from different "universes" that each have their own Array.
JS has many utterly insane design decisions, because there was no cohesive vision for the language. Bunch of people were like, hey, this feature would be convenient for my very specific protect, let's make the whole language like this forever.
Oh you tricky bugger. The 0 prefix indicates that the number is octal, except that as the first one has 8 as a digit is falls back to decimal. So this is 18 - 13 = 5
It’s not even that JS lacked a cohesive vision. It didn't have time to form one at all. Brendan Eich was forced to build it in 10 days just to ship it with Netscape, taking pieces from Java, Scheme, and Self and mixing them together.
Hence the popularity of TypeScript: “apparently no one will let me get rid of all these damn bear traps, so how about instead of just trying to remember where they all are at 5AM before I try coffee, I put up some actual guardrails around them?”
Yes, it coped but Java has abandoned and replaced it quite some time ago, there is no reason JS couldn't do the same. Furthermore I think a lot of what that site points at is down to string parsing.
PS: I looked it up and apparently JS has replaced it this year so my first point is largely moot.
To be fair, implicit type conversion between ALL types is a language design sin. It's why we need === and what not. There's a strong case to made that no language should have implicit type conversion. The more reasonable take is that languages shouldn't' automatically narrow convert. So like int to float is acceptable for implicit. But has anyone EVER been helped by objects automatically converting to [Object object] strings?
Yeah, unintuitive or misleading features are unintuitive and misleading. You can always say RTFM and be technically correct. They still are unintuitive and misleading.
“in” checks the keys, which are the indices in this case. 1 and 2 are valid indices, 7 is not as it is outside of the bounds of the array. So it does have something to do with the length of the array, yes.
That sounds like it's both the dumbest thing every yet also makes perfect sense at the same time. Knowing that everything knows JavaScript is a key-value object, it makes sense till a certain extend that it translates to "check if key 7 exists in the list" instead of "check if the value of 7 exists in the list".
Maybe it's because the second behaviour is what happens in Python, which I'm slightly more used to than JavaScripts semantics
Well, it does have to do with the array length. `in` searches an object's properties, array indexes are mapped to object properties and `in` finds them. `"length" in [1,2]` would also return true for the same reason.
I feel like this is a somewhat misleading description.
In JavaScript (no space) in checks whether a property name (a string) is available in a given object.
This operator isn't commonly used (nor really meant for) Arrays, but since an Array (and really almost anything) in JS is an Object, it still works there. Just maybe not how you'd expect.
Under the hood, [1,3,5,7] is represented something like this:
{"0": 1,"1": 3,"2": 5,"3": 7."length": 4}
So really it's not an "index number" because array indexes are strings, not numbers. Although, when you do something in object it coerces something to be a string.
JavaScript loves to coerce things because of its loosy-goosey type-system. This allows you to do powerful things, buts its responsible for like 95% of these "look how dumb JS is" gotchas.
it’s not python. if you don’t come from a python background, nothing about it is confusing. the syntax of js is different, and has its own ways of doing things.
there’s plenty of things to criticise js for, this is not one of them.
Oh no you have to look up syntax rather than going in cold turkey and getting upset your psuedocode doesn't work? Like every programming language ever? So surprising
In JavaScript, in checks whether an index exists, not whether a value is in the array. The array has indices 0–3, so 1 and 2 return true, while 7 returns false. Use .includes() to check for values.
No one who actually knows JavaScript would ever try to check for array membership using in. Just like no one who actually knows Python would check for list membership using list methods.
Source: I know both, regularly use both, and never run into this issue using either language.
More like putting 4+4 into a calculator and getting 16 because this particular calculator decided that + should mean multiplication rather than addition.
"in" checks the index, not the values. "3 in [1,3,5,7]" doesn't check if the value 3 is in the array it'll check if the index 3 is in the array. This behavior is more useful for things like umaps and it just happens to also work for arrays.
It feels like a sane language would say "this requires a hash map, sorry" instead of saying "cowabunga it is, arrays are just hash maps with indexes as keys".
No, it is like designing a calculator that uses the + symbol for multiplication and then blaming all the wrong calculations as user error. Making an in operator that does that was an astoundingly stupid decision at the language design level.
Bold of you to assume this behaviour was a design decision and not an unfortunate consequence of how arrays are implemented crossing over with how the in operator works.
Let's face it. The only reason we use javascript is because it's literally the only thing actually supported by browsers. Everything else about the language is atrocious.
Yes, but here we're talking about the fuss with in and the previous poster proposed has instead as if it was clearer. But both are trash at conveying they're about keys.
Any somewhat reasonable person would assume that in checks existence of elements in collections.
Any somewhat reasonable person wouldn't make random guesses regarding programming language syntax.
It's like complaining that 6 & 7 == 6 instead of True (or 67) in most programming languages. It's not intuitive that single logical symbols are bitwise and doubles are boolean. It's just convention.
I am almost exclusively dealing with bitwise operators in my code and when it's time to switch for double operands, I need to spend like 10 minutes rewiring my brain. Especially when you consider how easy it is to mistake && with & in certain scenarios.
So, most of the time, I just include iso646.h so I can write and, or etc. instead.
to be fair, [1,3,5,7] has 7 makes the same amount of sense. Every language has weird paradigms, "in" isnt meant to be used with arrays, but it works anyway just due to how the language is structured. IMO it should error which would solve this exact case, but technically there is nothing wrong semantically, so it just gives you an answer.
It would not be the end of the world if this was the only foot gun built into the language, but JS ist full of shit like that. Just look up how array sorting works.
People sometimes say that JS is a good beginners language. It's not. You have to learn so many tripwires, and until then, you will have such a frustrating experience.
People sometimes say that JS is a good beginners language
These people need a bop to the head, respectfully. Trying to understand data types is already a bit of a barrier in CS 101, but javascript types ? With stuff not being what they look like and implicit typecast with arbitrary rules ? Sheesh, I'd rather teach pointers.
all human languages have exceptions that you just need to know. what makes sense it just whats familiar. programming languages are for humans, not for machines. they compile into what is used for machines. therefore if everyone knows js and this doesnt freak them out, then its fine. no more weird than english having weird seemingly arbitrary spelling, or languages like spanish and italian having two forms of "to be" depending on the nature in which the thing or person is being. or how lots of languages have a subjunctive mood which is a special grammatical form things that don't really exist. to native speakers, they just think "well yeah, how else would you do it?"
Exactly. Nobody would come at it first and find “in” working like that familiar.
You’re comparing something that evolves randomly with no design intention, like a spoken language, to a programming language. By your argument, one could make a language where the plus sign multiplies. No more weird than English, no?
Sure. And once you get used to it, It's not such a big deal. That's absolutely true.
However, people make fun of weird language constructs all the time (It's one of my favourite YT categories). Kinda like this post.
Also, unlike real languages, programming languages are intentionally designed, so you'd assume they would avoid weird quirks like that, wherever possible.
If I want to meet with someone bi-weekly…. English literally has a word that has 2 different timeframes as definitions, twice a week and once every 2 weeks. There is literally 0 justification for it. At least JavaScript can explain these quirks
Programming languages are equally for humans and for machines. They exist precisely at the intersection of "describes computer instructions" and "legible by humans".
You are asking what indexes exist. Not for elements. A reasonable person would consider the complexity of having a simple operator to check elements in an array.
Not really. You use a language, you understand how its designed. In JS everything is an object. in is an operator to check if a key in an object exists.
Thats the whole logic behind it and its absolutely reasonable. Is it misleading for someone who doesnt know the language well enough? Absolutely. It would probably best to remove the in operator from the language altogehter, but that would violate compatability principle.
Usually people use array and object functions as that makes more sense since those can be applied due to the prototype behing it to the respective type of object. in has to be a generic operator as its not specific to a certain type of object.
If I was teaching a college course to students on the topic of "How bad design happens," I think your post would be a good illustration of that.
There seems to be this cognitive fault in people where, once they've learned how a bad design works, they become resistant to the idea that it's a bad design. It's like a tiny baby version of Stockholm syndrome.
You say "In JS everything is an object [and] in is an operator to check if a key in an object exists." Cool. Now we've described a bad design. Other, better languages would instead go with a good design.
The in operator isn't a in values of check, it's a in keys of check, and arrays are objects.
Two slightly weird decisions that combine to make an obscenely weird one: calling a contains key operator in, and treating arrays (at least from a language capability standpoint) as hashmaps with numeric property keys.
I don't really like that the in operator exists at all here. Relic of a much older era of JavaScript that still sticks around in our far far ES6+ era.
What's the issue? The operator does what it's supposed to do.
in checks if a key exists on an object, traversing up the prototype chain as well.
const obj = { a: 2, b: 5 };
"a" in obj; // true
"c" in obj; // false
You can think of an array as a special object that has numbers (actually, strings with the value of the given number) as its keys, which are the indexes of the elements.
const realArray = [1, 2, 3];
const fakeArray = {
0: 1,
1: 2,
2: 3,
length: 3, // putting this here for later so it's an array-like object
};
1 in fakeArray; // true, the key "1" is there
1 in realArray; // true, same reason
2 in fakeArray; // true, the key "2" is there
2 in realArray; // true, same reason
3 in fakeArray; // false, the key "3" is not there
3 in realArray; // false, same reason
What's even more fun is that you can use proper array methods on the fakeArray above if you set the function's this to the fakeArray.
Array.prototype.push.call(fakeArray, 100); // fakeArray has no 'push' defined, but we can set the 'this' value of the 'push' method for this one execution
realArray.push(100); // this would be the equivalent with the real array
console.log(fakeArray);
/*
{
0: 1,
1: 2,
2: 3,
3: 100,
length: 4,
*/
It really pays off to learn about the language you're using.
For me the issue isn't "learn the language" it's the cognitive overhead required to keep track of things that a statically typed language just simply wouldn't allow. Remembering that 'in' is for keyed objects is not the issue, it's that objects without keys are treated as having them via an implicit index. That's a type issue, not an 'in' issue, and should never be allowed! How am I supposed to safely use 'in' on something that I don't know what it is? If the answer is to do a type check, then having 'in' do double duty at that point is useless. I now have a branch by which to do a type specific lookup operation! I just don't get it.
I don't mean any of this perjoratively, if anything it's impressive to me people put up with this stuff and manage to be productive. Maybe I'm not smart enough? I like the warm cozy embrace of static typing and analysis simply not allowing me to do anything dumb. It removes so much mental load while programming to not have to remember arbitrary trivia in order to keep track of how my type is going to get interpreted by everything.
Right, also if you really wanna bash javascript logic there are LOT better examples if you look at null, undefined, -1 and how equality generally works lol
It's not counter intuitive at all, in checks object keys, that's it. It's only counter intuitive if you don't know the language, but the same argument could be used for any other language you don't know as well.
"why doesn't Rust allow reusing this value the same way C does? It's counter intuitive"
Sure, but once you learn it, it all comes together.
The point of intuitiveness is that you can correctly guess how something works without knowing it. It's like saying: "Yeah the function named 'ThisFunctionChecksIfTheAccountExists()' checks if the user has premium but it's actually really intuitive once you know that."
I really like JS (well, mostly TS nowadays), but this one does irk me.
I wish they never added `in`. TBH I don't love any of those weird operators that could just as easily be methods/functions. Stuff like `of`, `in`, `typeof`, ... It's syntactical sugar that just feels unnecessary.
i check if a number is prime if it equals to a number from my primeNumArray which stores strings of binary characters that represent prime numbers in base10
def checkPrime(n): for i in primeNumArray: if n==int(i,2): return true return false
2.7k
u/SpamOJavelin 11d ago •
The `in` operator checks for a property or field name, not values. In the case of an array, the field names are the keys. In this case the properties of the object are 0,1,2,3 - so 7 is not a property of this object.
If you use the correct operator, it makes sense:
89
u/jyajay2 10d ago
Obligatory https://jsdate.wtf/
150
u/Rajarshi1993 10d ago
It checks for the indices lmao
120
u/ramriot 10d ago
Putting aside languages that suck, let's talk about JavaScript, WAT!.
148
u/[deleted] 11d ago
`in` is specifically to test if the object/array index or key exists.
2 in [1,3,5,7] is true because array[2] exists. array[7] does not.
Yeah, it's a bit silly with arrays. But makes a lot more sense for objects. `"property" in {"property": 3}` for example
79
u/docgok 11d ago
Array.prototype.includes() was added in 2016, 21 years after Javascript shipped.
96
u/xubaso 10d ago
'length' in [1,3,5,7] => true58
u/KCGD_r 10d ago
"in" is the field name, or in the array's case, the index. It's looking for the 7th item of the 4-item array.
If u want to check inclusion, use [1,3,5,7].includes(7)
53
u/teerre 11d ago
It seems that the best programming talk of all time has been forgotten https://www.destroyallsoftware.com/talks/wat
99
u/1_hele_euro 11d ago
So why is this? Has this to do with the array length fuckery?
479
u/Top-Permit6835 11d ago
Oh my who'd've thought
58
u/Arodim88 10d ago
In JavaScript,
inchecks whether an index exists, not whether a value is in the array. The array has indices 0–3, so1and2return true, while7returns false. Use.includes()to check for values.const c0 = [1,3,5,7].includes(1); // true
const c1 = [1,3,5,7].includes(2); // false
const c2 = [1,3,5,7].includes(7); // true
30
u/cat-meg 11d ago
Ah I missed this. The return of JS bad so refreshing after ten thousand vibe coder bad posts. Nature is healing.
42
u/BitcoinBishop 10d ago
When you have to know a language to use it
63
u/rover_G 11d ago
It’s not python dude
11
u/ProfCupcake 11d ago
What is this weird version of this comic? Is it like a sticker or fridge magnet or something?
185
u/evenstevens280 11d ago edited 11d ago
Because
inisnt the correct operator for this task.It's like putting 4 × 4 into a calculator and getting annoyed that the answer isn't 8
24
u/DiamondDramatic9551 11d ago
Let's face it. The only reason we use javascript is because it's literally the only thing actually supported by browsers. Everything else about the language is atrocious.
61
u/da_Aresinger 11d ago
ITT: people with Stockholm Syndrome, desperately trying to justify insane language design.
Any somewhat reasonable person would assume that
inchecks existence of elements in collections.Testing for keys can be a different operator. Maybe
obj has key12
u/Professional-Day7850 11d ago
Name a duo that has driven more people into alcoholism than JS and PHP.
39
u/TerdSandwich 11d ago
You mean I have to read the documentation AND use basic reasoning????
4
u/Ill_Schedule_6450 10d ago
Garbage in, garbage out as usual
8
u/bevelledo 11d ago
This is like getting mad that Spanish says hola instead of hello
9
u/sessamekesh 11d ago
One of the many many footguns about JavaScript.
The
inoperator isn't ain values ofcheck, it's ain keys ofcheck, and arrays are objects.Two slightly weird decisions that combine to make an obscenely weird one: calling a
contains keyoperatorin, and treating arrays (at least from a language capability standpoint) as hashmaps with numeric property keys.I don't really like that the
inoperator exists at all here. Relic of a much older era of JavaScript that still sticks around in our far far ES6+ era.8
u/JackNotOLantern 9d ago
I don't think you know how "in" operator works in js, and you assume this is the same as python. It's not
21
u/Acclynn 11d ago
I disagree with all the comments saying it's a skill issue
It's an actual retarded design of this language
Not having this keyword at all would have been better
4
u/the_genius324 11d ago
well that's just because in is for objects (which is everything that isn't a primitive, sometimes including null but not in this case)
10
u/Alokir 11d ago edited 11d ago
What's the issue? The operator does what it's supposed to do.
inchecks if a key exists on an object, traversing up the prototype chain as well.You can think of an array as a special object that has numbers (actually, strings with the value of the given number) as its keys, which are the indexes of the elements.
What's even more fun is that you can use proper array methods on the
fakeArrayabove if you set the function'sthisto thefakeArray.It really pays off to learn about the language you're using.
2
u/EdgarDrake 11d ago
OOT, but I kinda miss SrGrafo content... does he still post somewhere in some subreddit (no longer active in r/funny)?
2
u/luiluilui4 11d ago
Can I tell my ide to show "doc comments" for operators and constructs like in? Would be so nice
2
u/Mayeru 10d ago
i want to know, why 2 is true and 7 false?
3
u/Ilastria 10d ago
Totally not nuts to let the „in“ operator check for the existence of an index when applied to an array
3
u/Phamora 10d ago
What? A language with opaque keywords?!
I think JavaScript must be the only one. Let's make fun of it!
3
u/EyesOfTheConcord 11d ago
I suggest not doing that then
3
u/exotic_anakin 11d ago
I really like JS (well, mostly TS nowadays), but this one does irk me.
I wish they never added `in`. TBH I don't love any of those weird operators that could just as easily be methods/functions. Stuff like `of`, `in`, `typeof`, ... It's syntactical sugar that just feels unnecessary.
3
u/MagicalPizza21 11d ago
This makes sense if you're designing a programing language without considering how programmers expect keywords to work.
1
u/imnota4 10d ago
https://youtu.be/et8xNAc2ic8?is=5qxfKf0NNdJ_No3a
1
u/yota-code 10d ago
Mandatory https://www.destroyallsoftware.com/talks/wat
1
u/tatstytastycakes 10d ago
javascript arrays have enlightenment
they know what is and isn't truthy
so they are truthy to prove it
1
u/Lunam_Dominus 10d ago
who_would_have_thought
1
u/Roxerg 9d ago
written by a python user
1
u/Academic_Pool_7341 9d ago
Nah rust is better
1
u/throwaway563125685 6d ago
Actual JS REPL:
1
u/Big-Capital-4048 5d ago
I only use JavaScript to write Frida scripts. For those purposes it works great. I would not want to use it to manage a UI however.
1
u/Ronin-s_Spirit 4d ago
JS is a good language (at least of the ones I tried or even looked at). And this is just writing wrong code for the sake of memes...
1
u/SneakyDeaky123 10d ago
If your language was written in 2 weeks, it’s probably not a good language
1
u/Juandice__ 11d ago
i check if a number is prime if it equals to a number from my primeNumArray which stores strings of binary characters that represent prime numbers in base10
"how do i create the primeNumArray?"
good question, shut up