javascript array length – How to Check if a JavaScript Array is Empty or Not with .length Example

javascript array length – The length property sets or returns the number of elements in an array. the length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

javascript array length (JavaScript Array length Property)

The JavaScript array length property states the number of items in an array.

Return the length of an array:

const players = ["Banana", "Rohit", "Virat", "Mango"];

1) Dense arrays

let players = ['sachin', 'dhoni', 'blue'];
console.log(players.length); // 3

The following adds one more element to the players array:

console.log(players.length); // 4

Now, the length property of the players array is four.

When you empty the players array, its length is zero:

players = [];
console.log(players.length); // 0

2) Sparse arrays

numbers[10] = 100;
console.log(numbers.length); // 11

Modifying JavaScript Array length property

1) Empty an array

const players = ['Virat', 'Rohit', 'Rahul'];
players.length = 0;

console.log(players); // []

2) Remove elements

const players = ['Virat', 'Rohit', 'Rahul'];
players.length = 2;

console.log(players); // [ 'Virat', 'Rohit' ]

3) Make array sparse

const players = ['Virat', 'Rohit', 'Rahul'];
players.length = 5;

console.log(players); // [ 'Virat', 'Rohit', 'Rahul', <2 empty items> ]

Don’t Miss : Javascript Length Of Array

I hope you get an idea about javascript array length.
I would like to have feedback on my
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.