r/ProgrammerHumor • • 11d ago

Meme whoWouldHaveThought

Post image
5.7k Upvotes

625 comments sorted by

2.7k

u/SpamOJavelin 11d ago • Mindblown Heartwarming

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:

[1,3,5,7].includes(1) => true
[1,3,5,7].includes(2) => false
[1,3,5,7].includes(7) => true

943

u/wannabe414 11d ago

Why does the in operator work on arrays at all

1.5k

u/klaustrofobiabr 11d ago

Everything is an object

517

u/Gladwulf 11d ago • Popcorn

don't objectify me!

803

u/javascript 11d ago • Popcorn Heartwarming Bravo

My bad

376

u/WeebOnDiscord 11d ago

Holy shit it's john javascript in the flesh

→ More replies (1)

235

u/Inforenv_ 10d ago

javascript

his tag is C++

peak

→ More replies (2)
→ More replies (7)

8

u/danielcw189 10d ago

not everything, but Arrays are

→ More replies (1)

33

u/NiIly00 11d ago

Just because it is an object doesn't mean we should always be allowed to treat it like an object. Especially if it creates nonesense like this.

Why would you ever need to use an "in" check on an array instead of just comparing against it's length?

69

u/bmacks1234 11d ago

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.

38

u/AlwaysHopelesslyLost 11d ago

You don't seem to understand what web programming looked like 30 years ago.

→ More replies (1)

27

u/captainAwesomePants 11d ago

You might want to check whether a property, like "length", exists for an object that may or may not be array-like.

→ More replies (7)

9

u/conundorum 10d ago

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.)

→ More replies (1)
→ More replies (21)
→ More replies (20)

32

u/StarInABottle 11d ago

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.

34

u/maria_la_guerta 10d ago

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.

→ More replies (2)
→ More replies (2)

6

u/Blue_Moon_Lake 10d ago

Because typeof [] === "object" and in work on any object.

→ More replies (1)

11

u/Atulin 11d ago

Because

const x = [ 1, 2, 3 ];
x.foo = 'bar';
'foo' in x // true

14

u/PhatOofxD 11d ago

It works but any linter will yell at you. So in practical terms no chance it ever happens

33

u/KerPop42 11d ago

Because JavaScript is usually run in a safe enough environment that unexpected behavior is better than crashing

16

u/HeKis4 11d ago

Which made sense back when it was just a fun way to add some interactivity to web pages. Not as the backbone of the UI of 90% of apps we use today...

24

u/Vizeroth1 11d ago

Sounds like people should rethink what they’re doing with JavaScript rather than blaming JavaScript for being what it has always been

→ More replies (3)
→ More replies (1)

30

u/gnuban 11d ago

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.

40

u/DaWolf3 11d ago

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.

→ More replies (1)
→ More replies (25)

4

u/Ozymandias_1303 10d ago

Because javascript would always rather give an answer than not give an answer, even if it's being asked a question that makes no sense.

3

u/w_w_flips 11d ago

Because JavaScript apparently has been written in roughly two weeks

→ More replies (1)
→ More replies (3)

227

u/stumpychubbins 10d ago

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.

25

u/remimorin 10d ago

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.

77

u/HolyGarbage 10d ago

Something sufficiently misleading is indistinguishable from being wrong.

7

u/tr14l 10d ago

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

→ More replies (9)

92

u/_dictatorish_ 11d ago

So it's bascially a dictionary and using "in" is just searching the keys?

Essentially {0: 1, 1: 3, 2: 5, 3: 7}?

Can't quite figure out why they'd make "in" operate like that lol

93

u/SpamOJavelin 11d ago

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.

12

u/failedsatan 10d ago

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 instanceof your window's Array, or if .prototype.toString() returned "[object Array]" (though you could reassign this function too).

don't you just adore Javascript? :)

7

u/Blue_Moon_Lake 10d ago

Slight correction: Array.isArray exists because instanceof Array can fail when passing values from different "universes" that each have their own Array.

→ More replies (2)

3

u/UsAndRufus 11d ago

Method calls are just pointers behind the scenes, as are dictionaries. It's the same mechanism.

16

u/JoenR76 10d ago

This. Javascript has enough real headscratchers in it that you don't have to resort to this one.

→ More replies (10)

26

u/Librarian-Rare 10d ago

I think you missed the point.

Compare this to Python.

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.

Like could you guess what this returns?

018 - 015

41

u/Faholan 10d ago

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

12

u/inoffensiveLlama 10d ago

It makes sense the way you explained it. Still… I wish I could unknow what I have just learned…

→ More replies (6)
→ More replies (3)

15

u/kaplotnikov 10d ago

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.

9

u/the_horse_gamer 10d ago

SyntaxError: Octal literals are not allowed in strict mode

→ More replies (1)

6

u/mixalhs006 10d ago

I can't and at this point I'm too afraid to ask lol

→ More replies (1)

16

u/ModernLarvals 11d ago

Who would’ve thought that an OP complaining about JavaScript doesn’t actually know anything about JavaScript.

37

u/Batman_AoD 11d ago

Knowing how to avoid footguns doesn't make them not footguns. 

→ More replies (4)

18

u/HeKis4 11d ago

If someone puts a dozen bear traps in my house you bet I'm going to complain, even if I know where they are...

4

u/Bartweiss 10d ago

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?”

2

u/Adventurous_Tie_3136 9d ago

So basically arrays are hashmaps in js where the indices are the keys.

→ More replies (5)

89

u/jyajay2 10d ago

31

u/the_horse_gamer 10d ago

javascript's date library was copied from Java's old one. that one's their fault.

6

u/jyajay2 10d ago

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.

8

u/the_horse_gamer 10d ago

Temporal (the new library) is great, much better than many other languages'

it sucks that it took this long, but at least that ensured it got the time it needed

also it's missing format string support (formatting a date into a format like "dd/MM/yyyy" you specify by input) which is annoying.

→ More replies (2)
→ More replies (1)

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!.

17

u/robin_888 10d ago

Classic! (Although array[16] of course actually only gives you 15 commas/separators, not 16 as he claims.)

3

u/Training-Home-1601 10d ago

Great video, thanks for sharing!

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

71

u/Trudae 11d ago

OP probably coming from Python wheren ’in’ checks if there’s a matching element

25

u/JuvenileEloquent 10d ago

"Javascript is so stupid, look what it does!"

looks inside

Cretin has abused type conversion with an inbuilt operator for a different type

Every time.

22

u/[deleted] 10d ago

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?

→ More replies (2)

3

u/danielcw189 10d ago

Cretin has abused type conversion with an inbuilt operator for a different type

there is no type conversion here. arrays are objects.

→ More replies (1)

79

u/docgok 11d ago

Array.prototype.includes() was added in 2016, 21 years after Javascript shipped.

11

u/DiamondDramatic9551 11d ago

What did you use before this?

49

u/BlaCoiso 11d ago

.indexOf(val) >= 0 (or !== -1)

16

u/Neither-Effort7052 11d ago

Gaps like this are why lodash/underscore/etc. exist.

→ More replies (14)

96

u/xubaso 10d ago

'length' in [1,3,5,7] => true

30

u/the-liquidian 10d ago

Because length is a key in an array. Which is what in checks for.

22

u/Notakas 10d ago

Very readable for humans

7

u/the-liquidian 10d ago

Yes, like pets.includes("cat")

→ More replies (8)

58

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)

13

u/froglicker44 10d ago

These complaints always come from people who don’t understand what they’re complaining about

26

u/CarolXZosiaNsfwScene 10d ago

Yeah, unintuitive or misleading features are unintuitive and misleading. You can always say RTFM and be technically correct. They still are unintuitive and misleading.

→ More replies (14)

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?

265

u/Prozilla6 11d ago

“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.

15

u/1_hele_euro 11d ago

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

6

u/howarewestillhere 11d ago

If you ask for pointers the right way you get the value you want and if you ask the wrong way you get an answer from the Old Gods.

→ More replies (2)

53

u/frikilinux2 11d ago

"in" in a array checks the size not the contents?

Is the abstraction this broken or was the language designer high? In addition to doing a quick job

113

u/Reashu 11d ago

"in" checks the keys of an object/record/dict. Arrays are just objects with integer keys.

→ More replies (29)

7

u/klequex 11d ago

It’s not an array operator per se, but arrays are js objects and so you can use it on them. It doesn’t “check” the size of

3

u/StarHammer_01 11d ago edited 11d ago

Yes. In checks the size (technically property but whatever). Contains checks the content.

In is useful for checking if an op is in bounds without checking the size of an array (intent is more clear).

3

u/alexanderpas 11d ago

in checks the keys of a collection, such as an object. (property in object checks if the object has a the property)

.includes checks the contents of an array.

→ More replies (3)

2

u/Esava 11d ago

Yeah, some other languages just have different names for it.

Like arr.get(7).is_some() in Rust (though that technically checks if the index is accessible, not whether it exists), PHP array_key_exists(7, $arr).

Such functions are even more common for maps (obviously). Like in java map.containsKey("7"), Ruby hash.key?("7"), Rust map.contains_key("7") etc..

→ More replies (7)

3

u/klequex 11d ago

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.

7

u/E_T_Dragoon 11d ago

Java Script uses in as a command to check if an Index Number exists. To check for the values in it you would need to check with .includes

7

u/exotic_anakin 11d ago

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.

→ More replies (2)

479

u/Top-Permit6835 11d ago
[1,3,5,7].includes(7) => true

Oh my who'd've thought

240

u/roodammy44 11d ago

Ahh yes, you have to do it this way. Not the other almost identical looking way that does something you wouldn’t expect…

90

u/ILKLU 11d ago

JavaScript Roulette:
which one is the foot gun?

9

u/roodammy44 11d ago edited 11d ago

It’s lucky we have bits of software that run on top of our languages to tell us which bits we should avoid.

30

u/exotic_anakin 11d ago

I'd argue that `7 in [1, 3, 5, 7]` does not look *almost identical* to that. But yea, that IS awkward and I don't like it.

→ More replies (9)

7

u/itgforlife 11d ago

TIL JavaScript is not Python

3

u/Feathercrown 11d ago

Isn't this true in every programming language?

15

u/TimeToBecomeEgg 11d ago

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.

16

u/RainEls 11d ago

Seems confusing coming from English background 

→ More replies (1)
→ More replies (3)

2

u/QuarkyIndividual 10d ago

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

→ More replies (2)

2

u/itgforlife 11d ago

You can also use some(). Although it requires more typing since it requires a callback function:

console.log([1, 3, 5, 7].some((e) => e === 2)); //false
console.log([1, 3, 5, 7, 2].some((e) => e === 7)); //true
→ More replies (1)

58

u/Arodim88 10d ago

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.

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/itgforlife 11d ago

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.

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 in isnt the correct operator for this task.

It's like putting 4 × 4 into a calculator and getting annoyed that the answer isn't 8

45

u/-TV-Stand- 11d ago

But it's the same symbol just rotated a little!

175

u/titanotheres 11d ago

More like putting 4+4 into a calculator and getting 16 because this particular calculator decided that + should mean multiplication rather than addition.

24

u/Taletad 11d ago

The "in" key word doesn’t have that convension at all

Most of the time it is used as an iterator for an array

With the syntax for X in Array

8

u/K1ngjulien_ 10d ago

funnily enough you use of if you want this behaviour in js.

 for (const element of array)

for.. in iterates over keys, screwing you over in the funniest way imaginable 🫩🫩

→ More replies (20)

22

u/Pure_Material_9235 11d ago

Perfect response.

→ More replies (11)

4

u/Experiment_1234 11d ago

What is in then

22

u/Mik3DM 11d ago

it's meant for objects to see if a key is present, in the context of an array, it's referencing an index.

3

u/el_yanuki 11d ago

checks for the existence of the array key aka length < x because JS treats arrays as objects

→ More replies (7)

4

u/Zincette 11d ago

"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.

9

u/GabuEx 11d ago

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".

10

u/Zincette 11d ago

I dont believe in sane programming languages. Sane people don't make programming languages

→ More replies (6)

7

u/not_a_burner0456025 11d ago

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.

5

u/anzu3278 11d ago

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.

→ More replies (2)

6

u/Koromann13 11d ago

Yeah. It should break, because using "in" on an array to check if that value is among the keys is stupid behavior.

That's why languages throw errors when something illogical is done.

10

u/_PM_ME_PANGOLINS_ 11d ago

JavaScript arrays are objects.

JavaScript is also designed to avoid throwing an error wherever possible, same as HTML.

→ More replies (3)
→ More replies (6)

2

u/lrrelevantEIephant 11d ago

In the vast majority of languages this would not be the expected behavior of the 'in' operator

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. 

3

u/Blue_Moon_Lake 10d ago

Yep, I would never touch JS, Ruby, Python, or PHP if I wasn't forced to.

2

u/Noslamah 6d ago

Yes, I hate how common Python has become as well. All typeless languages can fuck off as far as I'm concerned

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 in checks existence of elements in collections.

Testing for keys can be a different operator. Maybe obj has key

18

u/Blue_Moon_Lake 11d ago

And then someone would make the same meme with

[1,3,5,7] has 1 => true
[1,3,5,7] has 2 => true
[1,3,5,7] has 7 => false

5

u/examinedliving 11d ago

Except js has includes which would work with this

4

u/Blue_Moon_Lake 10d ago

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.

→ More replies (9)

11

u/Appropriate_Eye3906 11d ago

Why would you assume something instead of simply reading the documentation to ensure you are using something properly?

Do you not learn about a language before you implement things or do you just guess at shit?

24

u/dorox1 11d ago

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.

3

u/Regeneric 11d ago

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.

4

u/Blue_Moon_Lake 11d ago

That's why for logic I prefer keywords (and, or, not, xor).

3

u/earthqaqe 10d ago

A reasonable take on JavaScript? Am I in the wrong sub or what?

→ More replies (2)

8

u/KCGD_r 10d ago

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.

→ More replies (2)

21

u/Bob_Dieter 11d ago

That!

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.

15

u/HeKis4 11d ago

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.

5

u/ineyy 11d ago

See, if you survive it, you are already a veteran. Lol.

→ More replies (1)
→ More replies (1)
→ More replies (2)

5

u/Impossible_Dog_7262 11d ago

Or, y'know.

in obj.keys 

2

u/Blue_Moon_Lake 10d ago

Can't work with JS because you can make an object { keys: something }

Best you could have is Object.hasKey(obj, key).

→ More replies (7)

6

u/tuxedo25 10d ago

Any somewhat reasonable person would consult the documentation before using an operator they are not familiar with.

→ More replies (2)

6

u/cuntmong 11d ago

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?"

6

u/quantinuum 10d ago

> what makes sense is just whats familiar

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?

→ More replies (1)

5

u/da_Aresinger 10d ago

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.

4

u/fynn34 10d ago

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

→ More replies (5)

2

u/programgamer 6d ago

Programming languages are equally for humans and for machines. They exist precisely at the intersection of "describes computer instructions" and "legible by humans".

2

u/Ebuall 10d ago

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.

9

u/Bubbly_Address_8975 11d ago

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.

14

u/GregBahm 11d ago

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.

4

u/hopingforabetterpast 10d ago edited 10d ago

In JS everything is an object.

typeof (() => {})                 // 'function'
(() => {}) instanceof Object      // true

typeof "abc"                      // 'string'
"abc" instanceof Object           // false
typeof 5                          // 'number'
5 instanceof Object               // false
typeof true                       // 'boolean'
true instanceof Object            // false
typeof Symbol()                   // 'symbol'
Symbol() instanceof Object        // false
typeof 1n                         // 'bigint'
1n instanceof Object              // false
typeof undefined                  // 'undefined'
undefined instanceof Object       // false

typeof null                       // 'object'
null instanceof Object            // false (???)
Object(null) === null             // false (?????)
typeof Object.create(null)        // 'object'
Object.create(null) instanceof Object // false (?¿?‽‽! an object that isn't an object)
→ More replies (2)
→ More replies (2)

2

u/HeKis4 11d ago

I love how the high level language tries to do everything kinda like the human language but not quite.

→ More replies (8)

12

u/Professional-Day7850 11d ago

Name a duo that has driven more people into alcoholism than JS and PHP.

7

u/examinedliving 11d ago

Php like JavaScript has gotten a lot better but array methods in php used to be batshit insane

3

u/Blue_Moon_Lake 10d ago

Problem with PHP is that it has the ability to run a webserver but tells you never to use it.

→ More replies (5)

39

u/TerdSandwich 11d ago

You mean I have to read the documentation AND use basic reasoning????

6

u/YesterdayDreamer 11d ago

And apparently you can't use python syntax in Javascript. Atrocious, I tell you!

2

u/Blue_Moon_Lake 10d ago

I can't wait for a Python user to try using indentation instead of {} while writing JS.

8

u/oofy-gang 11d ago

I don’t even think you need both. It’s probably an OR situation.

5

u/ProThoughtDesign 11d ago

As long as it's not an XOR. That leads to people pushing to prod on Friday and shutting down the FAA.

5

u/dorox1 11d ago

Read the documentation -> "Wow, I use includes instead of in"

Basic reasoning -> "I should read the documentation" -> "Wow, I use includes instead of in"

Checks out!

→ More replies (3)

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 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.

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

→ More replies (1)

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

6

u/DiamondDramatic9551 11d ago

Naming matters

3

u/Blue_Moon_Lake 10d ago

Not having it would prevent you from checking if an object has a key efficiently.

→ More replies (4)
→ More replies (6)

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)

5

u/Feathercrown 11d ago

null is never an object, except when typeof lies and says it is. One of the few actual mistakes in JS.

4

u/Blue_Moon_Lake 10d ago

I wish typeof null said "null"

→ More replies (2)

3

u/JollyJuniper1993 10d ago

There’s always an explanation, that still doesn’t make it intuitive.

10

u/Alokir 11d ago edited 11d ago

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.

11

u/Rabbitical 11d ago

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.

4

u/Blue_Moon_Lake 11d ago

If you use JS/TS properly you never need in anyway.

→ More replies (4)
→ More replies (5)

4

u/sebbdk 10d ago

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

7

u/Mancks 11d ago

Is not about learning a language or not, it's about it being counter intuitive, it's somewhat pedantic to even defend it 

3

u/Alokir 10d ago

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.

3

u/ResponsibleWin1765 10d ago

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."

→ More replies (1)
→ More replies (1)
→ More replies (13)

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?

13

u/Lithl 10d ago

x in y checks if object y contains the property x.

Arrays are objects which have properties of their indices.

The last line is false because arr[7] is undefined.

3

u/Mayeru 10d ago

thank you! that makes sense (in a strange, not intuitive way)

→ More replies (1)

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

4

u/exotic_anakin 11d ago

"doctor, it hurts when I do this"

"stop doing that"

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.

→ More replies (7)

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/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:

>> (!![]+[])[+[]]+(!![]+[])[+!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!+[]+[])[+!+[]]+(![]+[])[+!+[]+!+[]+!+[]]

← "tears"

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

def checkPrime(n): for i in primeNumArray: if n==int(i,2): return true return false

"how do i create the primeNumArray?"

good question, shut up

2

u/Juandice__ 11d ago

fuck idk proper Markdown

whatever man

→ More replies (1)