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 :)

Comments

Popular posts from this blog

8 Things you should not be afraid of as a Developer

News

Why REST is so important