DEV Community 👩‍💻👨‍💻

Discussion on: Introduction to JavaScript Strings

Collapse
lukeshiru profile image
Luke Shiru

Adding to the article, you can also use " besides ' to define a string:

const obiWan = "hello there";
Enter fullscreen mode Exit fullscreen mode

And to loop over the characters in a string you have other options such as...

const greeting = "hello";

// Using for..of
for (const character of greeting) {
    console.log(character);
}

// Using Array.prototype.forEach (after turning it into an array with Array.from)
Array.from(greeting).forEach(character => console.log(character));

// Same with spread:
[...greeting].forEach(character => console.log(character));

// Same with Array.prototype.split
greeting.split("").forEach(character => console.log(character));
Enter fullscreen mode Exit fullscreen mode

And if you wonder which one is faster, here you have a perf comparison (you might think is the for..of ... and you would be wrong).

Cheers!

Collapse
naftalimurgor profile image
Naftali Murgor Author

Great insight!

Collapse
romeerez profile image
Roman Kushyn • Edited on

There is something interesting about turning a string to array, would you like a quiz?

// all are true:
typeof x == 'string'
x.length == 2;
[...x].length == 1
Enter fullscreen mode Exit fullscreen mode

What was the x? :)

Collapse
lukeshiru profile image
Luke Shiru

IDK if this is for me, but I take it: x was a UTF character made of others, like emojis with skin colors. You can use Intl.Segmenter to avoid this issue.

Thread Thread
romeerez profile image
Roman Kushyn • Edited on

Was for you, okay I'll mention next time, you're right!

x = "💩"
Enter fullscreen mode Exit fullscreen mode

thanks for the link - I never heard of Segmenter