DEV Community

Jan Küster
Jan Küster

Posted on

JavaScript puzzle - get length of an Array without using length

Write a function fn that returns the length of an Array as Number.


  • no use of length property
  • size and length/size indicating properties of other data structures are also not allowed


  • try to avoid the comments section, as the solutions are often posted there
  • it's way easier than you might think (which is why it's tagged #beginners)
  • read about Array fundamentals
  • don't expect the solution to be something that you should ever use in production code


console.assert(fn([]) === 0)
console.assert(fn([1]) === 1)
console.assert(fn(['1']) === 1)
console.assert(fn(['1', 2, {}]) === 3)
Enter fullscreen mode Exit fullscreen mode


This is all achievable by using 20 characters (inkl. function declaration) overall.

Top comments (5)

lexlohr profile image
Alex Lohr

Push returns the length; otherwise one could use recursion:

let l=a=>a.push()
// or recursive, but too long:
let l=(a,i=0)=>i in a?l(a,i+1):I
Enter fullscreen mode Exit fullscreen mode
devdufutur profile image
Rudy Nappée • Edited

const fn = arr => arr.reduce(acc => acc + 1, 0);

frankwisniewski profile image
Frank Wisniewski • Edited

16 chars using push...
In my opinion, this is not a solution because push returns the new array length.
If I solve it recursively, the smallest variant is 26 chars long.
Therefore I would be interested in the 20 chars solution.

jankapunkt profile image
Jan Küster

The puzzles are not looking for solutions, that are valid to be used in the real world (I should have mentioned that in the article). It's more intended to make people think out f the box and have a fun way to do some research about fundamental functionalities. From such a viewpoint, a push solution would be sufficient as it would comply with fn = Array => Number.

kateshim625 profile image

Thank you for the info!