Array Length

Every JavaScript array automatically maintains a .length property that returns the total count of items it currently holds.

const foods = ["burger", "fries", "pizza"];

console.log(foods.length); // Output: 3

Practical Example

The .length property is extremely useful for safely accessing the very last element in an array, without needing to know exactly how long the array is beforehand.

function getLastUser(usernames) {
  // Check if the array is empty
  if (usernames.length === 0) {
    return null;
  }
  
  // The last index is always the length minus 1
  const lastIndex = usernames.length - 1;
  return usernames[lastIndex];
}

const users = ["Alice", "Bob", "Charlie"];
console.log(getLastUser(users)); // Output: "Charlie"