Uses for Array length

0 Jeff Gong · September 15, 2015
I don't see how you would ever use the array length. Can someone tell me why you would use that?

Post a Reply

Replies

Oldest  Newest  Rating
0 rj m · September 16, 2015
If you make an array, and need to pull the information out of it, it is very useful to use a for loop.

A for loop requires a condition in which to keep looping until it is not true (boolean). That being said, if you need to get every element out of your array, and your array may vary in length depending on what has been done to it, you will need a variable to tell you how many times to loop through your array to pull out pieces of data one at a time.

That variable would be the array length

So, if you have an array like:

[1, 2, 3, 4, 5, 6], and you want to pull each value out for some reason, you would have a loop that looked like:

for (var i = 0; i < arrayLength; ++i) {
x = array[i];
}




Honestly the example has no real application, but if you needed to iterate through an entire array for some greater purpose, using the array's length as a variable will help make code construction easier while avoiding errors that stem from attempting to get data from an index in the array that does not exist (which would likely happen if the array changed throughout the program)

Hope that helps clear that up a bit!
0 Jeff Gong · September 16, 2015
thanks
0 Brotsky Tv · September 21, 2015
Read these Articles :

1) http://stackoverflow.com/questions/9901950/javascript-count-of-array-elements
2) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
3) http://stackoverflow.com/questions/14202601/array-size-vs-array-length


For more Javascript Tutorials : https://www.brotsky.tv/category/javascript/
  • 1

Javascript

107,048 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators