How to find length of an array without using functions in JavaScript and Ruby. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to find length of an array without using functions in JavaScript and Ruby.

Question Edited I want to know behind the algorithm of arr.length

30th Oct 2020, 1:03 AM
Balaji
Balaji - avatar
10 Answers
+ 9
In Javascript length is a property not a function. In other words it is a variable that is simply returning the value that is held. In Ruby length or size are both methods. You can achieve something similar by using a for each style loop with a counter variable. def len(arr) count = 0 arr.each do count += 1 end return count end items = [1, 2, 3, 4, 5, 6] puts len(items)
30th Oct 2020, 1:41 AM
ChaoticDawg
ChaoticDawg - avatar
+ 8
Thanks for editing. There is no algorithm involved. The length is just an internally stored attribute of the array (in ruby ​​it is a method that returns this attribute). An empty array has length 0. When we add x elements, we add x to the length. When we remove x elements, the length is subtracted by x. That's it.
30th Oct 2020, 1:46 AM
Kevin ★
+ 8
I agree with @ChaoticDawg In many languages array length is fixed during compiling time and won't change during runtime. I'll take the risk of saying that most (if not all) of the dynamic-length data structures that keep track of a length property will follow the simple method i shared before.
30th Oct 2020, 2:06 AM
Kevin ★
+ 6
No, not ALL programming languages follow this. Most OOP languages do something similar, but lower level languages may not or don't have a length function or property at all and you'd need to calculate the value based on the size of the array and the size of the type of an element in the array.
30th Oct 2020, 2:01 AM
ChaoticDawg
ChaoticDawg - avatar
+ 6
This is where getting familiar with MDN for Javascript can come in handy: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
30th Oct 2020, 2:21 AM
David Carroll
David Carroll - avatar
+ 4
arr.length Why would you need something else? Your question is unclear.
30th Oct 2020, 1:24 AM
Kevin ★
+ 2
def len(arr) count = 0 arr.each do count += 1 end return count end items = [1, 2, 3, 4, 5, 6] puts len(any item) This way
30th Oct 2020, 4:45 AM
Yuvraj Singh Sandhu (Inactive)
Yuvraj Singh Sandhu (Inactive) - avatar
+ 2
Thanks for helping you all.
31st Oct 2020, 4:59 AM
Balaji
Balaji - avatar
+ 1
Is that rule follows all programming languages with different implementation.
30th Oct 2020, 1:56 AM
Balaji
Balaji - avatar
+ 1
every array has that thing "length" you dont need to understand how it's work its a buit-in peoperity so you can just use it in js like this array_name.length
30th Oct 2020, 7:45 PM
Ahmed Bousaleh
Ahmed Bousaleh - avatar