JavaScript puzzle - get length of an Array without using length

Jan Küster - Feb 20 '22 - - Dev Community

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

Constraints:

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

Tips:

  • 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

Tests:

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

Bonus:

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player