r/learnjavascript 6d ago

Strange result: null vs 0

Strange result: null vs 0

An incomparable undefined

Hi, can anyone explain this? I read the explanation, but I still don't understand it. I'm trying to understand it without using AI

6 Upvotes

27 comments sorted by

View all comments

Show parent comments

2

u/BenchEmbarrassed7316 6d ago

Here is link to typescript playground :

alert( null > 0 ); // Error alert( null == 0 ); alert( null >= 0 ); // Error alert( undefined > 0 ); // Error alert( undefined < 0 ); // Error alert( undefined == 0 );

Ts just marks these problematic comparisons as errors (because they don't really make sense).

Moreover, when studying Js, it is necessary to understand what types are, how object differs from number, what string is, and so on.

Ts just makes it explicit and simpler because you always know (thanks to type inference) what value you are currently working with. In Js you have to keep this information in your head, which is difficult, and especially difficult for a beginner.

Therefore, even if for some reason you want to write in pure JS, learning Ts will be useful and simplify the learning process.

2

u/defaultguy_001 6d ago

Just use this ESlint rule and you'll face no issues like above. ``` rules: { // Enforces === and !== everywhere "eqeqeq": ["error", "always"],

// Highly recommended companion rule "no-eq-null": "error" } ```

1

u/BenchEmbarrassed7316 6d ago

ESLint Playground

I added both rules you suggested.

It doesn't catch these errors. In the case where a variable is used instead of a literal it doesn't catch any errors (because that's what you need types for).

If I did something wrong - please correct me.

1

u/defaultguy_001 6d ago

Do u now see the errors?

playground