Solve - length is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - length is not a function Error #

The "length is not a function" error occurs when we try to invoke the length property like a function instead of accessing it using dot notation. To solve the error, access the length property without parenthesis, e.g. arr.length.

typeerror length is not a function

Here are some examples of how the error occurs.

index.js
// โ›”๏ธ On Arrays const arr = [1, 2]; const r1 = arr.length(); // โ›”๏ธ Using jQuery const boxes = $('.box'); const r2 = boxes.length(); // โ›”๏ธ On strings const str = 'hello'; const r3 = str.length();

To solve the error, remove the parenthesis after the length property.

index.js
// โœ… On Arrays const arr = [1, 2]; const r1 = arr.length; // โœ… Using jQuery const boxes = $('.box'); const r2 = boxes.length; // โœ… On strings const str = 'hello'; const r3 = str.length;

Length is a property we can access on multiple types in JavaScript, e.g. - Array.length, String.length, NodeList.length.

When working with arrays, you have to be mindful that the length property sets or returns the number of elements in the array.

The length property always returns an integer with a positive sign.

The property can also be set by the user.

Here are examples of truncating an array by setting it's length property to a lower value.

index.js
const arr = ['a', 'b', 'c']; arr.length = 1; console.log(arr); // ๐Ÿ‘‰๏ธ ['a'] arr.length = 0; console.log(arr); // ๐Ÿ‘‰๏ธ []

After setting the array's length to 1, only the first element remained in the array.

Setting an array's length property to 0 empties the array.

And here is an example of setting an array's length to a higher value.

index.js
const arr = ['a']; arr.length = 3; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', , ] console.log(arr.length); // ๐Ÿ‘‰๏ธ 3

After we set the array's length to a higher value, the array got filled with empty elements.

All of the empty elements in the array are non-iterable.

It's extremely rare and considered a bad practice to see programmers change the array's length value.

That's because there are specialized methods that allow us to manipulate an array, that work in a more predictable manner.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee