2

I have JavaScript method as below,

function showMsg(id) {
  id = id! = null && id != undefined ? id : '';
  //doing some task
}

this showMsg(id) is getting called from different event with id having some value but onLoad event its not required any parameter so I am calling this method as below on Onload event

function onLoading(){
    showMsg(null);
}

will it cause any issue? Currently it's behaving right. But still I want to know about the issue I might face while calling the method with null as parameter.

Any Suggestion help must be appreciated.

5
  • until you have a check on the param for null its okay to have it. Commented Apr 17, 2017 at 8:29
  • refer stackoverflow.com/questions/2647867/…
    – Anil
    Commented Apr 17, 2017 at 8:30
  • id=id!= null&& id!= undefined ? id: ''; short id=id||""; Commented Apr 17, 2017 at 8:30
  • are you using es6? You can then set a default value to the variable id
    – Mμ.
    Commented Apr 17, 2017 at 8:32
  • Also as you check it, theres no difference betweem showMsg(null); and showMsg(); However, if your code is used by other people, i would keep the null to show that the parameter was not forgotten Commented Apr 17, 2017 at 8:32

3 Answers 3

3

Can I use null as parameter in method calling?

Short answer is YES, you can use null as parameter of your function as it's one of JS primitive values.

Documentation:

You can see it in the JavaScript null Reference:

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values.

And you can see from the documentation that:

In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

So in other words it can replace any other expected object and specifically a function parameter.

Note:

While you can pass null as a function argument, you have to avoid calling a method or accessing a property of a null object, it will throw an Uncaught ReferenceError.

1
  • 1
    Thanks you very much for you help
    – Zia
    Commented Apr 17, 2017 at 8:45
0

In JavaScript, parameters of functions default to undefined, but its fine to pass null as a paramter in JS functions if need be.

-1

You can check for null inside the function definition. Javascript functions are variadic in nature. So, you can choose to call it without any parameter. All you need to do is check if id is undefined inside the function. One way would be:

    function showMsg(id){
     if(!id) { //This would check for both null and undefined values

     }else {
       //logic when id is some valid value
     }
    }

   You should add any other checks per your requirements. This is just to mention that you don't even need to bother to pass any parameter.

Not the answer you're looking for? Browse other questions tagged or ask your own question.