Reputation: 1011
I have a js function as below
function showMsg(id) {
id = id! = null && id != undefined ? id : '';
//doing some task
}
I am calling above function from two different event one with parameter and another without parameter as below,
Call from first event,
showMsg(id);
Call from second event
showMsg();
As i know JS function is variadic in nature so is it right way to call the function? Will it cause any problem in older version of brwoser?
Any help and suggesstion must be appreciated.Thanks
Upvotes: 2
Views: 158
Reputation: 22500
Validate with simple If(id)
is enough. it validate undefined
, empty
,null
also and !
refer for id
is a false then stop the function execution .validate empty spaces use with if(id.trim())
=> trim()
function
function showMsg(id) {
if(!id){
return false
}
//doing some task
return id;
}
console.log(showMsg('hi')) //with argument
console.log(showMsg()) //without argument
Upvotes: 1
Reputation: 386680
You can shorten it to
id = id || '';
All falsy values are converted to an empty string. So as undefined
, which is the value for calling the function without a parameter.
Upvotes: 3