One Hundred and Fifty-Three

  • Random
  • Archive
  • RSS
  • Ask me anything

Things people write in JavaScript that make me angry and probably indicate they daren’t look past their pre- and misconceptions about the language and just fucking program, part 1

if(typeof something !== 'undefined' && something !== null)

As “the” “correct” way to check for an undefined variable.

Argh.

First things first, nothing is ever null unless you’ve told it to be. If you’re setting something to null, you’re never going to want to check if it’s undefined. So we can remove that:

if(typeof something !== 'undefined')

Sure: this works as a catchall. But anyone with any shred of sense, self-decency and knowledge about the values being passed around doesn’t need this kind of generality.

In fact, most of the time you can get away with:

if(something)

All this trips up on is 0, false and the empty string.

For a Number, we can use isFinite:

> isFinite("hello");
false
> isFinite(5);
true
> isFinite(0);
true
> isFinite(undefined);
false

Booleans have the old “strictly equal to false” trick:

> undefined === false
false
> false === false
true

As for Strings, are you ever really going to need to differentiate between undefined and the empty string? How is passing in an empty string better than passing in nothing?

  • 5 months ago
  • Comments
  • Permalink
  • Share
    Tweet

Recent comments

Blog comments powered by Disqus
← Previous • Next →

About

Avatar 153 Ways That Things Can Go Wrong and Then Awesomely Right, or Inventive Solutions to Problems That Don't Exist

Me, Elsewhere

  • Facebook Profile
  • quartertotomorrow on Flickr
  • mattyb1000 on Last.fm
  • Google
  • quarterto on github

Following

Cool Shit

See more →
  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr