4 Mar
2011

Basic JavaScript Part 11: Functional Initialization

Category:UncategorizedTag: :

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.

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.