2

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

Zia
  • 1,001
  • 1
  • 13
  • 25
  • 1
    This will be fine even in ancient browsers. You may or may not only want to check for only `undefined`. And take a look at https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in?rq=1 – Thilo May 26 '17 at 07:07

2 Answers2

3

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.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    This will change `showMsg(false)` , `showMsg(null)` and `showMsg(0)` to `showMsg("")` (which is probably okay here, and if it is, it would also be my preferred idiom). – Thilo May 26 '17 at 07:10
1

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
prasanth
  • 22,145
  • 4
  • 29
  • 53