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.

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Zia
  • 1,080
  • 10
  • 23

3 Answers3

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.

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
0

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

dattebayo
  • 992
  • 7
  • 4
0

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.
Pankaj Shukla
  • 2,435
  • 2
  • 9
  • 17