Question
Although you can explicitly check if a value is true or false, it’s a convention in JavaScript to test against all falsy values. For example, we can test if a variable value is falsy by testing if (value).
Code
function UnconventionalDefaults(params, defaultParams) {
if (params === undefined) {
params = defaultParams;
}
// function would do work here
return params;
}
// Modify this function to set params to defaultParams if params
// is falsy
function moreConventionalDefaults(params, defaultParams) {
// do a more conventional check here (check if params is falsy,
// and not just undefined
if(params === undefined){
params === defaultParams;
}else if(params === null){
params === defaultParams;
}else if(params === ""){
params === defaultParams;
}else if(params === false){
params === defaultParams;
}
return params;
}
Although I’m testing against all the falsy values, this code is not being accepted. What is it that I’m doing wrong? Is there a better way to do it?
You cannot use
===for assigning into params. Use=instead.Also those are not all falsy values, you are missing
0andNaN.The whole method can be simplified into:
paramswill be evaluated and if it is falsy then thedefaultParamswill be returned.EDIT: Have a loot at great article Exploring JavaScript’s Logical OR Operator by Addy Osmani for more information.