How do I check if a list is empty?

How do I check if a list is empty?

Hey Shreshthaseth,

Using the length property:

let list = []; if (list.length === 0) { console.log(“The list is empty.”); } else { console.log(“The list is not empty.”); }

This method checks the length property of the array. If the length is 0, the array is empty.

Hello Shresthseth,

Using the Array.isArray() method in combination with the length property:

let list = []; if (Array.isArray(list) && list.length === 0) { console.log(“The list is empty.”); } else { console.log(“The list is not empty or it’s not an array.”); }

This method first verifies that the variable is an array using Array.isArray(). It then checks if the array’s length is 0 to determine if it is empty.

Hello Shreshthaseth,

Using the == operator to check if the array evaluates to a falsy value:

let list = []; if (!list.length) { console.log(“The list is empty.”); } else { console.log(“The list is not empty.”); }

This method uses the ! operator to check if the length of the array is 0, which is a falsy value in JavaScript. If it is falsy, the array is empty.