Check whether a given value is an array before subjecting it to array methods.
Loose typing can be a pain when your methods are being called from other methods / external modules. It is a good idea to check for valid types to avoid throwing runtime errors that are difficult to understand or parse.
Using type checks is one such practice. As seen earlier, type checks is easily done for primitives.
|
|
So, how about an array?
|
|
All complex types return ‘object’, which may or may not be useful depending on what you are doing with that.
If we are doing array operations on an object, we would very much like an array in the input. We can do two things to validate -
Option 1: Use isArray()
Use Array
prototype method to check whether a given input is indeed an array.
|
|
Option 2: Use Object Prototype
|
|
Validate whether our code works -
|
|
You can make this code reusable for different types of objects with a simple change -
|
|