r/javascript • • Mar 02 '19

Useful javascript one-liners.

https://medium.com/@smellycode/js-one-liners-8bc0a6af2345?source=friends_link&sk=a9295a05aef9e514e137fca7eeb89cd1
344 Upvotes

96 comments sorted by

View all comments

43

u/Shaper_pmp Mar 02 '19

Why on earth would anyone use a font for programming that runs characters together and makes it difficult or impossible to determine whether something is a double- or triple-equals?

With a language like JS that's just asking for trouble...

5

u/taniket Mar 02 '19

If you are using double = rather then triple, there's something wrong with your code other than the font.

-1

u/benihana react, node Mar 02 '19

that's great in theory and all. but in practice, on the web, a lot of values get coerced to strings, so it's not really that straightforward.

sometimes you have to deal with the fact that something that is represented as 35 in your database will be represented as "35" in your UI. Using strict equality will lead to subtle bugs in these kinds of situations.

8

u/folkrav Mar 02 '19

There's something wrong with your architecture if you're straight up comparing DB and UI values. For the odd time these things happen, I still much prefer to go with strict equally and cast manually. It's much easier to reason with, and easily testable.

-3

u/Shaper_pmp Mar 02 '19 edited Mar 02 '19

Not at necessarily - are you arguing against the entire concept of type-coercion here, or just claiming that there are always better ways to use it than testing for loose equality with ==?

2

u/adenzerda Mar 02 '19

I’m not the person you’re replying to, but personally I haven’t used explicit loose equality in years. Might be a symptom of working in a c# house, but it seems like each time I used to use it, it felt like it could have been done in a less sloppy way.

Exceptions, of course, granted to our humble friend if (!thing) { } (I know it has its own shortcomings to be conscious of but it’s usually fine)

0

u/Shaper_pmp Mar 02 '19 edited Mar 02 '19

You've never had a situation where a value can be a positive integer, 0 or null (say, retrieving the count of some resource via an async computation), and you only care if it's an integer greater than zero... or any other similar example of trinary logic (true/false/null)?

if (!thing) is just one example of a general class of problem, and you can only avoid the == if you happen to be coercing to boolean (not other types) and if you're comparing to a static value (rather than another variable).

Edit: Or a better example, say involving the result of an async operation that can return true or false, where null means "pending" when the operation hasn't yet completed:

if(asyncResultThatCanBeTrueFalseOrNull == thingThatCanBeTrueOrFalse) {
  // do something where we treat false and null the same
}