Basic JavaScript Part 11: Functional Initialization

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods
  8. Namespaces
  9. Reusing Methods of Other Objects
  10.  The Module Pattern

I just want to quickly share some beautiful JavaScript code I picked up while watching the most excellent screencast 11 More Things I Learned from the jQuery Source by Paul Irish.

var base = dom.getElementByTagName('base')[0] | | (function() {
     // Do some stuff
     return someElement.insertBefore(dom.createElement('base'), someElement.firstChild) ;
})(); 

This single line of code basically checks whether there’s a base tag somewhere in the DOM. If there is one, then it assigns the reference for the first element to the base variable. If it’s not in the there, then a self-executing function inserts a new base tag into the DOM and returns the reference to the new element.

I don’t know about you, but I think this is pretty neat.

Published by

Jan Van Ryswyck

Hi, thank you for visiting my blog and reading all the crap that I'm posting here. I'm a senior software engineer at SD WORX. Developing software is one of my greatest passions in life, and I enjoy doing it every single day. I've got three kids (Len, Lisa & Laura) who constantly remind me that there is more in life than just programming all day. They are the greatest kids in the whole world. And last but not least, there's my girlfriend who is my inspiration in life. You can always contact me at jan_dot_van_dot_ryswyck at gmail.com

2 thoughts on “Basic JavaScript Part 11: Functional Initialization”

  1. It is the old “do or die” Perl/PHP-like construct. Personally I think it should be used only with values, as it makes the code harder to read when used with embedded functions. Also, I assume dom is not the same as a browser document object, as the function name there is getElementsByTagName and if there is no ‘base’ element, the array would be null and the whole thing would throw an error.

  2. very nice, but in this case it seems a lot more clear to me to do it like this:

    var base = …;
    if (!base) {
    base = …
    }

Comments are closed.