DEV Community

Cover image for Destructuring Tweets - Episode 3 - Length of a Multiline-String

Destructuring Tweets - Episode 3 - Length of a Multiline-String

odddev profile image Kai ・2 min read

Howdy, welcome to OddDev's series about destructuring one of those JavaScript quizzes on Twitter. Welcome to this week's episode!

Snippet of the Week

This week's snippet is from Chris Kalmar:

const stars = `

console.log(stars.length * 2);
Enter fullscreen mode Exit fullscreen mode

They create a multiline string via Template Literal syntax. That is just a fancy way of saying they initialized it by using backticks (`foobar`). It offers some excellent features, one of them even being crucial for this blog post.
Well, then we output the length and multiply it by two.

The Output

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, tho. Even now, for our snippet, this is not the trickery! 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 62.


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. Adding up on 15 stars, we have a length of 25.
Second, Template Literals support multiline strings! We need to count every line break (\n) as well. Let us refactor the string declaration with regular apostrophes:

const stars = '\n\n  ⭐⭐\n  ⭐⭐⭐\n  ⭐⭐⭐⭐\n  ⭐⭐⭐⭐⭐\n';
Enter fullscreen mode Exit fullscreen mode

As you can see, we have six line breaks. These plus 25 characters add up to 31. Doubled in the output gives us 62.

Snippet Summary

Discussion (0)

Editor guide