salmon salmon - 1 month ago 8
Javascript Question

Javascript function parameters checking

I have a function with 4 parameters for building json request. I need to check parameters for 'undefined'/empty value

function funName(param1, param2, param3, param4) {
if (param1 !== '' && param2 !== '' && param3 !== '' && param4 !== '') {
url = https://example.com/api/posts.json?' + param1 + param2 + param3 + param4;
}
else if {
if (param1 == '' && param2 !== '' && param3 !== '' && param4 !== '') {
url = https://example.com/api/posts.json?' + param2 + param3 + param4;
}
// code
};


How to check more elegant ?

Answer

For your purposes you can do this:

function funName(param1, param2, param3, param4) {
   var url = 'https://example.com/api/posts.json?' + 
             (param1 || '') + (param2 || '') + (param3 || '') + (param4 || '');
   // rest of your code.
}

Or with ES6:

function funName(/* params */) {
   var url = 'https://example.com/api/posts.json?' + 
             [...arguments].filter(p => p).join('');
   // rest of your code.
   console.log(url);
}

funName('a=1', '&b=2', '');