[Solved] Which ways are best to define my method.


So, you’ve proposed two functions that look like they are primarily designed to work with arrays, but they should return intelligent results if you pass them something other than an array.

So, right away, you can’t use the Array.prototype method because if the data is not an array, that method won’t exist on the object and you won’t get the behavior you have currently coded.

So, it really comes down to whether they should be global functions or namespaced functions on your own global object.

When in doubt, fewer global symbols is generally the right answer because more global symbols make it more likely you may have a conflict with other code you might include in your project.

I would suggest this revised implementation of your namespace object:

var Helper = {
    isEmpty: function (obj) {
        return !obj || (Array.isArray(obj) && obj.length === 0);
    },
    pushArray: function (arr1, arr2) {
        if (Array.isArray(arr1)) {
            if (Array.isArray(arr2) {
               // push one array onto the end of the other
               arr1.push.apply(arr1, arr2);
            } else if (arr2 !== undefined) {
               // push a value onto the array
               arr1.push(arr2);
            }
        }
    }
}

In isEmpty(), I’ve removed the obj === null || obj === undefined checks because they will never be hit because !obj will already catch those.

In pushArray(), I’ve made it so a falsey value passed in arr2 (such as 0) can be pushed into the array which your code would not allow.

2

solved Which ways are best to define my method.