CD and DVD movies available for download at download movies portal, cheap prices. If you are searching for mp3s, you could try to download mp3 music at this mp3 portal. Super quality, high speed downloads.

*

2007 / June 22nd/ Exit with grace

One of the most common actions in javascript functions is checking if certain browser functionality is available before executing the function. Here’s a common pattern you’ll see:

function hide_flash(){
  // Check for browser functionality & presence of element
  if (document.getElementById && document.getElementById('flash')){
    // Hide the element and then change the settings
    document.getElementById('flash').style.display = 'none';
    flash_status = 'off';
    console.log("The flash has been turned off.");
  }
}

That’s all well and fine, but it’s not quite graceful. We’ve got a lot of unnecessary indentation. Here’s a quick tip: use the return statement of Javascript to exit the function instead of embedding your functionality in an if statement. Here’s the revised function:

function hide_flash(){
  // Check for browser functionality & presence of element
  if (!(document.getElementById && document.getElementById('flash'))) return;

  // Hide the element and then change the settings
  document.getElementById('flash').style.display = 'none';
  flash_status = 'off';
  console.log("The flash has been turned off.");
}

Much better! Keeping this idea throughout your code can clean up all sorts of validations, checks and keep your indentation the way it should be.

A word from the sponsors. Advertise with Warpspire

3 Comments

comments feed

  1. Gravatar
    Ben

    June 22nd | #

    Nice idea but your example is wrong.

    In the first version you do your check and if it’s true you hide the flash. In the second you do your check and if it’s true you return where you wanted to hide.

    I like the concept though and do similar things myself, although no doubt I could use this sort of thing a little more often - I do like to indent :)

  2. Gravatar
    Kyle

    June 22nd | #

    Sorry, one misplaced ! :) All fixed now.

  3. Gravatar
    chris rhee

    June 26th | #

    Awesome, I used this on about 3 different projects the same day I read it.

Make a Comment

don’t be afraid, it’s just text

Comments are parsed with Markdown. Basic HTML is also allowed.