CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Array Length: Find Array Length in Javascript

Shawpnendu Bikash Maloroy

May 9, 2024
Javascript Array Length Property
Spread the love

Table of Contents

  • 4 Most Important Points on array.length Property
  • JS Array Length Syntax
  • How to Find Array Length in Javascript?
    • Output image
    • Code Explanation
      • Output Image
  • Alternative Way to Find the Length of Array in Javascript
    • Output Image
    • Code Explanation
  • How to Iterate Over an Array in JS?
    • Output Image
    • Code Explanation
  • Shortening an Array Using Length
    • Output Image
    • Code Explanation
  • How to Create an Empty Array of Fixed Length?
    • Output Image
  • How to Make an Array of Void?
    • Output Image
    • Code Explanation
  • Define an Array with Non-Writable Length
    • Output Image
  • Javascript array Length vs. Size Comparison
  • Workaround to Javascript Array Length Undefined
  • Browser Compatibility List of Javascript Array Length Property
  • Conclusion
  • FAQs
    • How to find the length of an array in JavaScript?
    • What is length() in JavaScript?
    • Does array length start at 0 or 1 in JavaScript?
    • What if array length is 0 in JavaScript?
    • How to change array length in JavaScript?

The javascript array length property sets or returns the number of elements in an array. Length is the only property that provides us with an easy and efficient way to determine an array size. The value is an unsigned, 32-bit integer. Max size is a nonnegative integer less than 232.

For the first element of an array, the index number always starts at 0, whereas the length property always starts between 0 and 1. Zero, if no elements exist in the array.

Basically, the javascript array length is used to check whether an array is empty or not? If the array is not empty, then iterate through the elements using a loop.

4 Most Important Points on array.length Property

  1. JS array length is dynamic means, whenever we add an element to the array the array size will be increased accordingly and vice versa. But we can restrict it by using non-writable property. Don’t worry we will discuss more at latter part of this article. So bear with us.
  2. If the length is set to a value less than its current length, then elements that exceed the new length are removed.
  3. If the length is set to a value greater than its current length, then the length property is increased to the new highest index. Keep in mind that the additional array slot(s) not filled with undefined values. Check for details.
  4. If the length is set to an invalid value such as a negative number or non-numeric then JS throws a RangeError exception.

JS Array Length Syntax

Get the JavaScript Array Length:

arr.length

Set the JavaScript Array Length:

arr.length = number

How to Find Array Length in Javascript?

Javascript has an inbuilt length property to get the size of an array. The size is always a positive integer number.

Here is an example of how to use the .length property:

<script>
   let courses = ['Javascript','CSS','HTML','Asp.net']
   let totalCourses = courses.length
   console.log(totalCourses)
</script>

Output image

Javascript array length output

Code Explanation

Here in the above code, we are using an array named “courses” to store the course names. Later we used the variable “totalCourses”    to get the number of courses that we have stored in the courses array using the javascript array length property. After that we print the output in the console window and the output is 4 as expected.

Ok, now check the javascript array length property return datatype. As mentioned earlier the return type must be a positive integer number. Now prove it:

<script>
   let courses = ['Javascript','CSS','HTML','Asp.net']
   let totalCourses = courses.length
   console.log(typeof totalCourses)

   let kpiList = [12,13,14,25]
   let numberKpi = kpiList.length
   console.log(typeof numberKpi)

</script>

Output Image

Javascript array length return DT

Ok, so it’s now clear to you, and we hope you will never forget. In case of any doubt, not only for the length property but also for other javascript properties, you can use the typeof inbuilt operator for type checking.

Note

The typeof operator in Javascript is specially used for datatype checking of any operand (total courses, as per the above example). The operand can be a variable, object, or function.

Alternative Way to Find the Length of Array in Javascript

<script>
   
   function getArrayLength(arr)
   {
      let cnt = 0;
      for (const item of arr) {
      cnt++;
      }

      return cnt;
   }

   let courses = ['Javascript','CSS','HTML','Asp.net']
   console.log("Length of courses array is:", getArrayLength(courses));

</script>

Output Image

Find the Length of Array in Javascript

Code Explanation

In the above code block, we write a generic function to determine the length of any array passed in as an argument. We declared a variable named cnt and assigned 0 to it first. Upon receiving each element of the supplied array one at a time, we subsequently increase the value by 1.

To count the number of elements in the provided array, we used a for-of loop (not a general for loop) to check elements one by one in the array.

The purpose of the for-of loop is to iterate over the provided array until an undefined is encountered. This is the way we iterate over each and every element and increase our cnt variable until we reach the end of the array, “arr”. Once our for-of loop encounters the undefined value, the return line will be executed, and we get the cnt value as the length of the array “arr” finally.

We pass the array “arr” as the input to the function getArrayLength in order to get the length of the array as the returned value.

How to Iterate Over an Array in JS?

In the following example, we are going to iterate courses array using the javascript array length property. During iteration we also print the array elements in our console log.

<script>
   
   let courses = ['Javascript','CSS','HTML','Asp.net']
   let totalCourses = courses.length
   for (let i = 0; i < totalCourses; i++) 
   {
      console.log(courses[i])
   }

</script>

Output Image

How to Iterate Over an Array in JS

Code Explanation

Here in the above code we initialize our courses array with values [‘Javascript’,’CSS’,’HTML’,’Asp.net’].

And then stores the length of the courses array (which is 4) in the totalCourses length variable.

Now the for loop is ready to iterate over the courses array. Based on initialization the for loop starts with i=0 and continue iteration as long as the loop meet the length condition.

On each loop we print the array elements in our console log.

Shortening an Array Using Length

By using the JavaScript Array Length property you can get the length of an array. But here in the following example see how we can shorten the array courses to a length of 3. What is going to happen?

<script>
   
   let courses = ['Javascript','CSS','HTML','Asp.net'];
   courses.length=3;

   console.log(courses)

</script>

Output Image

Shortening an array in JS

Code Explanation

The courses array is initialized with [‘Javascript’,’CSS’,’HTML’,’Asp.net’].

Now we set the courses.length=3, therefore the array is truncated and keep only the first 3 elements. So the array now become to [‘Javascript’,’CSS’,’HTML’]. Discarded the last element from the array.

So, now if we print the array courses – it prints the truncated array like the above output screen.

How to Create an Empty Array of Fixed Length?

Alternatively if we set the array length to a higher value as mentioned in our “Most Important Points on array.length Property” section. Then it will create a sparse array.

<script>
   
   const courses = [];
   courses.length = 3;
   
   console.log(courses);

</script>

Output Image

js empty array with fixed length

How to Make an Array of Void?

If we set the length property of any array to 0 then the array is going to be void. Look at the below example:

<script>
   
   const courses = ['Javascript','CSS','HTML','Asp.net']
   courses.length = 0;
   
   console.log(courses);

</script>

Output Image

How to Make an Array of Void

Code Explanation

The courses array is initialized with four string values: ‘Javascript’,’CSS’,’HTML’,’Asp.net’.

The line courses.length = 0; sets the length of the courses array to 0. This line of code removes all elements from the array and making it empty or void.

The console.log(courses); line then prints the current state of the courses array.

As the array now emptied, the output is [], means a void array at all.

Define an Array with Non-Writable Length

By default, a javascript array is dynamic, which means the JavaScript Array Length property is automatically updated by the array in the event of element addition or deletion. But we can restrict it. If the length property is set to non-writable, then the array will not be able to update it. If we try to add or delete any element of the array, this causes an error in strict mode.

In this cases we are also unable to modify the values of the array.

<script>

   "use strict";
   
   const courses = ['Javascript','CSS','HTML','Asp.net']
   Object.defineProperty(courses, "length", { writable: false });
   
   courses[3] = ''; // ERROR > Uncaught TypeError: Cannot assign to read only property 'length' of object '[object Array]'
   
   courses.push(''); // ERROR > Uncaught TypeError: Cannot assign to read only property 'length' of object '[object Array]'

</script>

Output Image

Define an Array with Non-Writable Length

Javascript array Length vs. Size Comparison

Now we are going to figure out the actual difference between the array length and size. And also try to understand why this debate is still going on? Let’s see:

array.sizearray.length
array.size() is a functionarray.length is a property
array.size() is not a valid method means not a native JS functionIt’s a native property
Commonly used as a custom getter.Commonly used for array manipulation or iteration
You may need to add other library.JS native property
Not recommended to useSafe to use

Workaround to Javascript Array Length Undefined

It happens mainly for 2 reasons:

  1. Initialization issue: If the array is not initialized before calling. Then you will receive JavaScript Array Length undefined error.
  2. Type issue: May be you are using the length property on other type such as object instead of an array. Serialization issue also exist.

Browser Compatibility List of Javascript Array Length Property

BrowserCompatible?
ChromeYes
EdgeYes
FirefoxYes
SafariYes
OperaYes
IEYes

Conclusion

So far, we have discussed JavaScript array length in every aspect. From iteration to manipulation the length property is a must use property to work with arrays of different sizes and types.

Regarding the debate of size vs. length, we have clearly mentioned using the length over size method, as the size method is not a native JS method.

Still, do you have any confusion? Please write to us using our comment section.

FAQs

How to find the length of an array in JavaScript?

In short, use the array length property to get the size of any array irrelevant to DT. Don’t use the size method.

For example, arr.length will return the count of all elements in the arr array.

What is length() in JavaScript?

The .length is a built-in javascript property. It’s used to get the count of all elements in an array, the count of all characters in a string, and a lot more.

For example, if you have a string ‘javascript’ and call the . length property, then it will return 10 because the string ‘javascript’ has 10 characters. In the case of an array, let courses = [‘Javascript’,’CSS’,’HTML’,’Asp.net’]. The courses.length property will return 4, as the courses array has 4 elements.

Does array length start at 0 or 1 in JavaScript?

Javascript array index starts from zero (0). If you have an array of one element, then the first element index will be 0, but the length will be 1. The length property is used to get the count of an array. So don’t get confused.

What if array length is 0 in JavaScript?

Yes an array length could be 0. In this case the array is empty means does not contain any element. For example const arr = [];. Its length is 0.

How to change array length in JavaScript?

Yes, you can set the array length by any positive integer number, irrespective of its number of elements. For example, if you have an array of 5 elements and you set the length property value to 3, then the final array size will be 3, and it will discard the last 2 elements automatically.

But if you set the length to 7, then the final array size will be 7. Keep in mind that the additional array slots (here 2) are not filled with undefined values.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!
  • JavaScript No-Code Automation
    JavaScript No-Code Automation: How to Replace Zapier with a Few Lines of Code

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com