Search code examples
javascriptstring-length

Why does ({"word"}) return its length?


I'm puzzled by this solution to finding the length of a string:

const getLength = ({length}) => length

I'm familiar with object and array destructuring, but couldn't find anything about string destructuring(?) or how this would return the length. The concept of adding curly braces to the function parameter is also alien to me.


Solution

  • You're making a function that requests that an object parameter be destructured into just its "length" property. When you pass a string, the string will be coerced to a String instance so you get the "length" property value, which the function returns.

    See what happens when you try this:

    console.log(getLength({ length: "Hello world" }));