My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Saturday, February 09, 2008

The fastest way to know if someone "did it" ...

I know I choosed a weird title, isn't it :?

Today I have two small and useful tips and tricks for JavaScript.

The first one, lets you know if someone extended the Object.prototype

if((function(k){for(k in {})return true;return false})()){
// do stuff that care about Object prototype
} else {
// do stuff that doesn't care about Object prototypes
}

Simple, quick, and dirty ;) and this is another example:

function didIt(k){for(k in {})return true;return false};

if(didIt()){
// stuff prototype
}

One thing to take care about is the usage of a function instead of a variable.
Since some script could run other scripts dinamically, you can't trust in a single time check.

The second trick is really useful for function that accept a switcher argument.
For switcher argument I mean methods or function that accept true or false as argument.
The simplest way to have a switcher is obviously sending the value, but in this case we can't have a default behaviour.

Simple is to choose a "false" behaviour as default one

function addOrRemoveStuff(dontDoIt){
if(dontDoIt){
// someone sent a true value
} else {
// default behaviour, dontDoIt is false or undefined
}
}


So what's new? Nothing, yet, but try to guess about a different default ... a true value as default ... think ... think ... think ... did you find them? :)

function addOrRemoveStuff(doIt){
doIt = !arguments.length || !!doIt;
if(doIt){
// default behaviour, doIt is true
} else {
// someone sent a false value
}
};

addOrRemoveStuff(); // true
addOrRemoveStuff(false); // false
addOrRemoveStuff(1); // true


This simple thing is present, for example, in jQuery.smile method.

$("div.post, p.comments").smile(); // add smiles
$("div.post, p.comments").smile(false); // remove smiles

Enjoy these tricks, and this week end as well :)

3 comments:

  1. More directly what you want:

    if (doIt !== false)

    ReplyDelete
  2. David, You know that JS is not strongly typed, and you know that 0, null, or undefined, are evaluable as false ... and an empty strings as well.

    What I mean, is that my example is more portable, scalable, or flexible, while your one is obviously perfect, but for a strongly type language and not for a quick and dirty ECMAScript 3rd Edition :)

    Cheers

    ReplyDelete
  3. Hi Andrea, i just want to say thank you for all your shared thoughts/work/ideas. I find it hard to believe how your work (specially pack.it) isn't more 'spread' around the www.

    ReplyDelete

Note: Only a member of this blog may post a comment.