Hacker News new | ask | show | jobs
by wereHamster 2488 days ago
`if ('loading' in HTMLImageElement.prototype === true) {`

/rolleyes

1 comments

I'm missing why this is a bad thing?

It make polyfills way easier, and makes it drop-dead simple to programmatically toggle lazy-loading on existing elements.

I think the previous poster was referring to the unnecessary `=== true` part.
It's quite common to compare against "true" using "===" in JavaScript.
I wouldn't say it's common. Most JavaScript developers (who aren't familiar with JS coercion rules or the difference between == and ===) wouldn't even be able to tell you for certain what the code does, exactly.

Using === to compare against "true" makes only sense if the variable can be something other than boolean (undefined, null, string etc). Or if you are programming defensively – by choice or because the codebase is messy.

> Or if you are programming defensively – by choice or because the codebase is messy.

This accurately describes the majority of JavaScript projects I have worked on.

The last web agency I worked at even had linters checking against '=='.

See this table https://dorey.github.io/JavaScript-Equality-Table/ which displays how unsure you can end up when using '=='.

> Most JavaScript developers (who aren't familiar with JS coercion rules or the difference between == and ===)

It rings strange to me that you would believe that developers who focus on one language ("JavaScript developers") wouldn't know the quirks of that language. Not all JS devs are juniors.

I prefer to follow this rule, "never use == and != unless you need type coercion". You know that your expected results is 'true' then why not test for that only?

The `in` operator always returns a boolean, though.
Maybe it was just done out of habit.

A bool can be expected today. But why about 10 years from now? Defensive programming isn't a bad thing. Making assumptions is why we had the Y2K mess.