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

1
  • 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 stackoverflow.com/questions/5515310/… Commented May 26, 2017 at 7:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.