I was checking for an empty array wrong...How to check for an empty array in javascript?
In JavaScript, there are several ways to check if an array is empty. Here are the common methods:
Using the length
property: One way to check if an array is empty is to use its length
property. An empty array has a length
of 0, so we can check for an empty array by checking if its length
is equal to 0:
let myArray = [];
console.log(myArray.length ? true : false) // false;
But if we wanted to access a property or method on an object that might not exist, we would typically use a series of if
statements or ternary operators to check each level of the object for existence before accessing it. For example:
console.log(myArray && myArray.length ? true : false);
So, with the introduction of optional chaining in ES6 we can now access deeply nested properties or methods on an object, without having to check if each level of the object actually exists before accessing it in a more concise way.
console.log(myArray?.length ? true : false);
With optional chaining, we can simplify this code by using the ?.
operator to access each level of the object, and if any level of the object is null
or undefined
, the expression short-circuits and returns undefined
:
It is especially useful when working with APIs or data sources that may return incomplete or partial data, as it allows us to safely access the properties and methods that do exist without having to check each level of the object for existence manually.
Nullish coalescing operator
There is also another way that is used to provide a default value for a variable or expression that may be null
or undefined
, while explicitly excluding other falsy values such as 0
, false
, ""
, and NaN
The operator works by returning its left-hand side operand if it is not null
or undefined
, and returning its right-hand side operand otherwise. For example:
myArray = [{ id: 1 }];
console.log(myArray?.[0]?.id ?? "yes the id is here"); // 1
But let's consider a case for checking the property that does not exist in the array
console.log(myArray?.[0]?.name ?? "nothing is here"); //nothing is here
The nullish coalescing operator is useful when you want to provide a default value for a variable or expression, but want to treat null
and undefined
as distinct from other falsy values. It can help avoid bugs and unexpected behavior in code that relies on default values.