Javascript array length returns 0

JavaScript Array Length

Summary: in this tutorial, you’ll learn about the JavaScript Array length property and how to handle it correctly.

What exactly is the JavaScript Array length property

By definition, the length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

The value of the length is 2 32 . It means that an array can hold up to 4294967296 (2 32 ) elements.

The length property behaves differently depending on the array types including dense and sparse.

1) Dense arrays

A dense array is an array where its elements have contiguous indexes starting at zero.

For dense arrays, you can use the length property to get the number of elements in the array. For example:

let colors = ['red', 'green', 'blue']; console.log(colors.length); // 3Code language: JavaScript (javascript)

In this example, the length property returns three, which is the same as the number of elements in the colors array.

The following adds one more element to the colors array:

colors.push('yellow'); console.log(colors.length); // 4Code language: JavaScript (javascript)

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

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

colors = []; console.log(colors.length); // 0Code language: JavaScript (javascript)

2) Sparse arrays

A sparse array is an array whose elements don’t have contiguous indexes starting at zero.

For example, the [10,, 20, 30] is a sparse array because the indexes of its elements are 0, 2, and 3.

In a sparse array, the length property doesn’t indicate the actual number of elements. It’s a number that is greater than the highest index. For example:

let numbers = [10, , 20, 30]; console.log(numbers.length); // 4Code language: JavaScript (javascript)

In this example, the number of elements in the numbers array is three: 10, 20, and 30. The highest index is three. Therefore, the length property returns four.

The following adds an element to the numbers array at the index 10:

numbers[10] = 100; console.log(numbers.length); // 11Code language: JavaScript (javascript)

In this example, the length property returns 11.

Modifying JavaScript Array length property

JavaScript allows you to change the value of the array length property. By changing the value of the length, you can remove elements from the array or make the array sparse.

Читайте также:  Php not empty object

1) Empty an array

If you set length to zero, the array will be empty:

const fruits = ['Apple', 'Orange', 'Strawberry']; fruits.length = 0; console.log(fruits); // []Code language: JavaScript (javascript)

2) Remove elements

If you set the length property of an array to a value that is lower than the highest index, all the elements whose index is greater than or equal to the new length are removed.

The following example changes the length property of the fruits array to two, which removes the third element from the array:

const fruits = ['Apple', 'Orange', 'Strawberry']; fruits.length = 2; console.log(fruits); // [ 'Apple', 'Orange' ]Code language: JavaScript (javascript)

3) Make array sparse

If you set the length property of an array to a value that is higher than the highest index, the array will be spare. For example:

const fruits = ['Apple', 'Orange', 'Strawberry']; fruits.length = 5; console.log(fruits); // [ 'Apple', 'Orange', 'Strawberry', ]Code language: JavaScript (javascript)

Summary

  • The length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index of the array.
  • The length returns the number of elements that a dense array has.
  • For the spare array, the length doesn’t reflect the number of actual elements in the array.
  • Modifying the length property can remove elements from the array or make the array spare.

Источник

Array: length

The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Try it

Value

A nonnegative integer less than 2 32 .

Property attributes of Array: length
Writable yes
Enumerable no
Configurable no

Description

The value of the length property is a nonnegative integer with a value less than 2 32 .

const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length 

The array object observes the length property, and automatically syncs the length value with the array’s content. This means:

  • Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
  • Setting any array index (a nonnegative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
  • Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.

When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.

const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, ] arr.forEach((element) => console.log(element)); // 1 // 2 

Examples

Iterating over an array

In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.

const numbers = [1, 2, 3, 4, 5]; const length = numbers.length; for (let i = 0; i  length; i++)  numbers[i] *= 2; > // numbers is now [2, 4, 6, 8, 10] 

Shortening an array

The following example shortens the array numbers to a length of 3 if the current length is greater than 3.

const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3)  numbers.length = 3; > console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; the extra elements are deleted 

Create empty array of fixed length

Setting length to a value greater than the current length creates a sparse array.

const numbers = []; numbers.length = 3; console.log(numbers); // [empty x 3] 

Array with non-writable length

The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.

"use strict"; const numbers = [1, 2, 3, 4, 5]; Object.defineProperty(numbers, "length",  writable: false >); numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]' numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]' 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Check if a JavaScript Array is Empty or Not with .length

How to Check if a JavaScript Array is Empty or Not with .length

When you’re programming in JavaScript, you might need to know how to check whether an array is empty or not.

To check if an array is empty or not, you can use the .length property.

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

Let’s run through some examples.

Here’s an Interactive Scrim Showing How to Check if a JavaScript Array is Empty or Not with .length:

.length Example Syntax

Const myArray = [‘Horses’, ‘Dogs’, ‘Cats’];

Here we create a variable pointing towards an array.

Using the length property, we can check the length of the array:

This will return 3, because there are 3 items in the array.

To check if the array is empty or not with .length, we can do this in in three ways.

.length example one

First, let’s create a new array with no elements.

Now we can check if the array is empty by using .length .

This will return 0, as there are 0 items in the array.

.length example two

We can also explicitly check if the array is empty or not.

If our array is empty, the above message will get logged. If the array has elements in it, the code within the if block will not run.

Here’s the third way to check whether or not an array is empty using .length.

.length example three

By combining the use of the length property and the logical «not» operator in JavaScript, the «!» symbol, we can check if an array is empty or not.

The ! operator negates an expression. That is, we can use it to return true if an array is empty.

For this example, let’s open up our JavaScript console. To open up your console in Chrome, you can click Inpsect -> Console.

First, create an array with no items in it.

image

Next, let’s use the logical «not» operator, along with our .length property, to test if the array is empty or not.

Screen-Shot-2020-09-30-at-5.29.35-PM

If we had not used the «not» operator, arr.length would have returned 0 . With the operator added, it will return true if its operand is false . Because arr.length is 0 , or false, it returns true .

Let’s use this with an if statement, and print out a message if our array is empty.

image-2

When checking if an array is empty or not, it’s often best to also check if the array is indeed an array.

Because there might be the case when you were expecting to check the length of an array, but instead you’re given a different data type, for example, a string:

image-7

Because the length property can be used on other data types, it is good to also check that your array is indeed an array as you were expecting.

I suggest you also use the Array.isArray() method to confirm your array is an array. This method determines if whether what was passed in is an array or not. If what was passed in was an array, this method will return true .

Let’s add this method to our example.

How to use the Array.isArray() method

image-3

Wrapping up

In this article, we learned that you can use the length property in JavaScript in various ways to check if an array is empty or not. The length property returns the number of items in an array.

We also learned that it is best to also use the Array.isArray method when using the .length property, to check if the passed value is an array as you’re expecting.

Источник

JavaScript Array length

The length property sets or returns the number of elements in an array.

Syntax

Return the length of an array:

Set the length of an array:

Return Value

Browser Support

length is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью