Search code examples
javascripttyped-arraysuint8array

Why do TypedArrays have a static length property with value 3


I just came across this gem when looking up some Uint8Array properties:

TypedArray.length

    Length property whose value is 3.

I tried it and it is true!

wtf

What? Why does this exist?!


Solution

  • For functions, the length property is how many parameters are in its argument list. For the Uint8Array constructor, that number is 3.

    function example2 (a, b) {}
    function example3 (a, b, c) {}
    
    console.log(example2.length);
    console.log(example3.length);

    Regardless of the length property, any function can be passed any number of arguments, and the function can use or ignore all of them. So the length is just a hint about how many are likely to be used.

    // This function doesn't list any arguments, so it's length is 0
    function example () {
      // ...but it uses 2 anyway.
      console.log(arguments[0], arguments[1])
    }
    console.log(example.length);
    // .. and i can pass in more than 2, useless though it is.
    example('first', 'second', 'third');