DEV Community

Chandru
Chandru

Posted on

JavaScript Strings: The Basics I Learned

Strings are one of the first things we use when learning JavaScript.

Simply put, a string is just text.

There are three common ways to create strings in JavaScript.

1. Single Quotes

We can use single quotes to create a string.

let name = 'John';
Enter fullscreen mode Exit fullscreen mode

2. Double Quotes

We can also use double quotes.

let name = "John";
Enter fullscreen mode Exit fullscreen mode

Both single and double quotes work in a similar way. It's mostly a matter of which style you prefer or what the project uses.

3. Template Literals

Template literals use backticks instead of quotes.

let message = `Hello ${name}`;
Enter fullscreen mode Exit fullscreen mode

I find template literals especially useful when we need to include variables inside a string.

For example, instead of joining strings with +, we can directly put the variable inside ${}.

Some Useful String Methods

JavaScript has many built-in methods for working with strings.

We can change text to uppercase:

let text = "hello";
text.toUpperCase();
Enter fullscreen mode Exit fullscreen mode

Or lowercase:

text.toLowerCase();
Enter fullscreen mode Exit fullscreen mode

We can also check how many characters are in a string:

text.length;
Enter fullscreen mode Exit fullscreen mode

Another useful one is includes(), which checks whether a string contains some text.

text.includes("he");
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Strings may seem very basic, but we use them everywhere in JavaScript — names, messages, search boxes, URLs, API data, and much more.

The main thing to remember is:

Single quotes → 'Hello'

Double quotes → "Hello"

Template literals → `Hello ${name}`

Top comments (0)