How to check for an empty Array and why it is important?

Make it a rule of thumb to check for an array to be a valid array and checking if it’s empty before iterating or accessing its elements.

Take a look at the following function which iterates the array and returns the first element’s id.

function getDataId(arr){
  return arr[0]['id']
}

console.log(getDataId([{id : 10}])); // 10

console.log(getDataId([])); //  Uncaught TypeError: Cannot read property 'id' of undefined

console.log(getDataId("str")); // undefined

Since no check is there to confirm if the parameter passed to getDataIds is an Array and it’s not empty, it’s failing in the second and third scenarios.

Let’s put a check to see if the parameter is an Array and not empty.

function getDataId(arr){
  if(Array.isArray(arr) && arr.length > 0){
  	return arr[0]['id']
  }
  return 0;
}

console.log(getDataId([{id : 10}])); // 10
console.log(getDataId([]));          // 0 
console.log(getDataId("str"));       // 0

To be on the safer side, it’s also recommended to check for the object property before accessing it. The above code will break in the scenario when Array arr might be having objects not containing id property.

function getDataId(arr){
  if(Array.isArray(arr) && arr.length > 0 && arr[0].hasOwnProperty('id')){
     return arr[0]['id']
  }
  return 0;
}

console.log(getDataId([{id : 10}]));    // 10
console.log(getDataId([]));             // 0
console.log(getDataId("str"));          // 0
console.log(getDataId([{name : 123}])); // 0