Saturday, 14 June 2014

Setting default values for arguments in JavaScript

function complex (settings){
settings.option1 = (typeof settings.option1 === "undefined") ? "default option 1" : settings.option1;
settings.option2 = (typeof settings.option2 === "undefined") ? "default option 2" : settings.option2;
settings.option3 = (typeof settings.option3 === "undefined") ? "default option 3" : settings.option3;
settings.option4 = (typeof settings.option4 === "undefined") ? "default option 4" : settings.option4;

console.log(settings.option1);
console.log(settings.option2);
console.log(settings.option3);
console.log(settings.option4);
};
complex({option1: 'this is option 1', option3: 'this is option 3'});
image

JS Fiddle:  http://jsfiddle.net/stevenhollidge/w9z2g/

No comments:

Post a Comment