Destructuring Tweets – Episode 3 – Length of a Multiline-String
const stars = ` ⭐ ⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ `; console.log(stars.length * 2);
They create a multiline string via Template Literal syntax. That is a fancy way of saying they initialized it using backticks (
`foobar`). It offers some excellent features, one of them even being crucial for this blog post.
Well, then we output its length and double it.
Commonly the length of a string is described as providing the count of the characters. Technically, this is incorrect. Practically, most times, it's okay to think about it like that. Even now, for our snippet, this is irrelevant! We, indeed, only count characters.
Following that logic, the first thought is to count the stars (⭐) and multiply them by two, being
30. Surprisingly enough, this is far from reality. The output is
The analysis is relatively easy here when you know two things. First, two whitespaces indent every line of stars! They also need to be taken into consideration. For five lines, we have an extra ten characters. This adds up to 25 (10 whitespaces + 15 stars) total.
Second, Template Literals support multiline strings! We also need to count every line break (
\n). Let us refactor the string declaration with regular apostrophes:
const stars = '\n ⭐\n ⭐⭐\n ⭐⭐⭐\n ⭐⭐⭐⭐\n ⭐⭐⭐⭐⭐\n';
As you can see, we have six line breaks. These plus 25 characters add up to 31. Doubled in the output gives us 62.