javascript is array empty

Whether an array is empty or not depends on its contents. An empty array is one that has no elements – it is represented in JavaScript as [ ]. An array can be initialized with elements but still be considered empty if all the elements are empty themselves. For example, [ null, undefined, "" ] is considered an empty array, even though it has three elements.

If you want to check if an array is empty or not, one simple way is to check its length:

        let arr = [1, 2, 3];
        if (arr.length > 0) {
            console.log("Array is not empty");
        } else {
            console.log("Array is empty");

Here, we check the array's length attribute. If it is greater than 0, we know the array is not empty. Otherwise, it must be empty.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]