Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
uber Avatar asked Nov 12 '19 23:11

uber


People also ask

How do you find the length of a word in a string?

You can use string#split and then use map to get the length of each word.

How do you show the longest word in Python?

In this program, first we read sentence from user then we use string split() function to convert it to list. After splitting it is passed to max() function with keyword argument key=len which returns longest word from sentence.

How do I count how many times a word appears in Python?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.


1 Answers

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" }));
like image 105
Pointy Avatar answered Sep 19 '22 12:09

Pointy