OneBite.Dev - Coding blog in a bite size

check if array is empty in Javascript

Code snippet on how to check if array is empty in Javascript

  if (arr && arr.length > 0) {
    // Array is not empty.
  }
  else {
    // Array is empty.
  }

This code checks to see if an array is empty. First, it checks if the array exists by using the ‘if’ operator combined with the ‘arr’ variable. If the ‘arr’ variable exists, the code will move on to check the length of the array. If the length of the array is greater than 0, the code will run the code in the first set of curly brackets, which in this case is a statement saying the array is not empty. Otherwise, if the array has a length of 0 or is undefined, the code will run the code in the second set of curly brackets, which in this case states that the array is empty.

javascript