Programming in javascript leaves me often in doubt of what is the actual best method of doing things, since it’s such a permissive language.

So here is a couple of recurring questions that finally found an answer for me ( shamelessly found here ):

1./ How to set default values in a function ?

In php, it’s easy enough:

function doMeGood($foo = 'bar'){
echo $foo;
}

doMeGood() will print “bar”;

There is no such thing in javascript. The best solution is to pass an object as argument, and then inside the function set a default object and overwrite it with the object passed as argument:

myfunction({ c:5, a:22 });
function myfunction(passedArgsObj) {

/* defaults */
args = { a:1, b:2, c:3 };

/* override the defaults if necessary */
for (var argName in passedArgsObj) {
args[argName] = passedArgsObj[argName];
}

alert(“a = “+args.a);
alert(“b = “+args.b);
alert(“c = “+args.c);
}

2. What’s the best way to check for the existence of a variable?

I’m sometimes confused whether i should check for the existence of a variable and its set value. I’ve just learned that

If a parameter is not passed, it has a default value of undefined, not null. So you should check for the undefined value. Javascript performs implicit conversion when the == operator is used.


0 == null
false == null
undefined == null

This is why, the check for null is true if the parameter is not passed. But it is wrong, because if you pass an explicit value of 0, it will also evaluates to true.

You have to use one of these comparisons:

a) passed[i-1] === undefined
b) typeof passed[i-1] == "undefined"