WEB-DEV.CA

Those Strings!

To humans, strings are the foundation of how we interact with text. But to javascript developers, strings are a sequences of characters that can be manipulated in a variety of ways.

Parsing data is one of my favorite things to do and in this section, we'll take a deep dive into the nuances of JavaScript strings, ensuring you have a thorough understanding of their behavior, quirks, and best practices.

The Basics

Declaration

When we declare a string, they can be enclosed in single quotes 'abc', double quotes "abc", or backticks `abc`. These different notations aren’t just about syntax preferences but have different use cases.

One notable difference between single and double quotes is that you can embed a single quote within a string if you use double quotes and vice versa. However, if you are somehow stuck using one or the other, you can also embed a quote mark within a string if you escape it with a backslash.

Immutability

JavaScript strings are immutable. Meaning any operation done on a string, such as concatenation or slicing, always results in a new string rather than mutating the original one.

The great thing about immutability is it makes strings predictable when working with them. You can pass a string to a function without worrying that the function might alter the original string.

Immutability can also have performance issues, especially when doing data manipulation on large datasets. For example, if you repeatedly modify a string, each modification creates a new string, and the old ones might linger in memory until garbage collected. When concatenating large strings repeatedly, it’s often better to use arrays and join them at the end.