Home > front end >  Is it valid to have a JavaScript function that does nothing?
Is it valid to have a JavaScript function that does nothing?

Time:01-13

I'm working three texts boxes that get data and display them in a jQuery autocomplete drop down. Since JavaScript is rather flexible with it's objects and does not have interfaces. I made an API call object that then takes in an object of functions that gets spread into it's self.

export function ApiCall(baseUrl, domain, path, options = {}) {
    return {
        baseUrl: baseUrl,
        domain: domain,
        path: path,
        getData: function () {
            return $.ajax({
                url: this.fullUrl,
                dataType: "json",
                data: this.data,
                success: function(data) { return data }
            });
        },
        ...options
    }
}

This allowed me to get rid of the majority of if blocks since I no longer had to check for html IDs. I have however ran into two issues with this. Some of the objects need to have an empty function that does nothing while others have that function do something.

addError: function () {
                        addError(this.title)
                    },

and others

addError: () => { }

This is growing some and I'm worried that the objects might have some implanting them and others not. As is now the code is working great and it has cleared up many if blocks that do different things depending on what html ID is being passed around and just runs the function on the object. Is this valid? Any better ways to implement this? Any ways to clear this up so it's more readable and less confusing?

CodePudding user response:

Yes, no-op functions are encountered occasionally, and sometimes there's no way around them. But it usually makes more sense if, instead of writing no-op functions, you can omit the function entirely.

If there's code not under your control that unconditionally calls a property of an object, but you don't want anything to occur when that happens, then no-op functions are your only option.

But if the code that uses the object is under your control, you'll find that your code will be significantly slimmer if you check that the property exists before calling it. For example, if, given an object, you want to call addError on it if that property exists, you can do:

obj.addError?.();

allowing you to avoid having to do

addError: () => { }

everywhere.

If you have to use no-op functions instead, it's a bit unfortunate (IMO), but not a big deal.

  •  Tags:  
  • Related