On 5/14/15 4:22 PM, Gijs Kruitbosch wrote:
On 14/05/2015 19:08, Martin Thomson wrote:
If you intend to support false and null and undefined and NaN and
attribute the same semantics, _say so_.  Make it explicit.  Don't make
me (the person reading your code years later) that this is your
intent.

Then why is if (!foo) OK and do you not prefer:

if (foo === false || foo === undefined || foo === "" || ...)

? Why do I not have to make it "explicit" (which is a word I think
doesn't make sense here, see below) in that case?

Exactly. Nobody wants to outlaw if (foo) and if (!foo). Why is that?

Because JS comes with too many ways to say no: undefined, false, null, Nan, '', 0 (and they will all happen!)

More often than not, treating them all the same semantically (falsy) is more likely to be correct (and implicitly safer by being less verbose and you wont remember them all otherwise):

  foo(bar) {
    if (!bar) {
      baz();
    } else {
      fum(bar);
    }
  }

  foo({});
  foo(null);
  foo();

If we accept that statement, that testing for falsy is safer than testing the five no's explicitly, then the safer comparators seem to be: == and !=.

e.g. isn't

  foo(bar) {
    if (bar == null) {
      baz();
    } else {
      fum(bar);
    }
  }

  foo({});
  foo(null);
  foo();

safer than:

  foo(bar) {
    if (bar === null) {
      baz();
    } else {
      fum(bar);
    }
  }

  foo({});
  foo(null);
  foo(); // ugh undefined is more like null than {}!

?

Sure, we shouldn't write either, but then what about:

  foo(x,y) {
    if (x != y) {
      baz();
    } else {
      fum(x);
    }
  }

  foo({}, {});
  foo({}, null);
  foo({});
  foo(null, null);
  foo(undefined, null);
  foo(null);

?

.: Jan-Ivar :.

_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to