Understanding JavaScript String: an easy beginner’s guide with examples

Daminda Dinesh Imaduwa Gamage
8 min readMar 23, 2023
Photo by James Harrison on Unsplash

The JavaScript string is a fundamental topic that every developer needs to know, whether you specialize in front-end or back-end development. A guide to JavaScript strings is essential for gaining a sound understanding of this topic.

What is a JavaScript string?

In JavaScript, a string is a sequence of characters that can be used to represent text. Strings are a fundamental data type and can be either a primitive or object type. They are used in a wide variety of contexts, from simple text manipulation to complex string processing algorithms.

Javascript strings are immutable. This means you can not change a JavaScript string after it is created.

First of all, let’s see how to create a string in JavaScript.

String primitives vs String objects

Primitive strings are the most basic type of string in JavaScript. They are immutable, thus, they cannot be modified once created.

On the other hand, a string object is a wrapper around a primitive string and provides additional methods and properties for working with strings.

String objects are created using the String() constructor function, and can be modified using these methods. However, modifying a string object does not modify the underlying primitive string.

In general, it is recommended to use primitive strings whenever possible, as they are more efficient and easier to work with. String objects should only be used when you need to take advantage of their additional methods and properties.

How to create a JavaScript string

You can create string mainly in two ways:

  1. string primitives using string literals
  • const str1 = 'This is a string created using single quotes'
  • const str2 = "This is a string created using double quotes"
  • const str3 = `This is a string created using backticks. We can use ${variables} and ${expressions} inside backticks`

The string literal specified with a single quote or double quote has no difference.

The third option above uses template literals (specified with backquotes/ backticks ) and can also be used in string interpolation.

  1. String object using String constructor

const str4 = new String(‘This is a string created using String constructor.’);

As mentioned above, creating a string using the constructor is not recommended as it leads to unexpected behaviors, especially when comparing strings.

How to get the length of a string

You can use the length property to get the length of the string object.

const str = "Hello, World!";
const len = str.length;
console.log(len); // output: 13

Escape Character

When creating a javascript string, you use double or single quotes. But, what if you want to print something like below?

Mars, also called “The Red planet” will be inhabited one day.

Let’s see what happens If you include that sentence within double quotations.

let text = "Mars, also called “The Red planet” will be inhabited one day."

This will produce an error: Uncaught SyntaxError: Unexpected identifier “The Red planet”

The reason is that the JavaSript Ineterpeter will consider “Mars, also called “ as the string assigned string to the text variable, and thus for the Interpreter the phrase “The Red planet”, is not within double quotations even though you and I can see that from our own eyes.

So, how to fix this?

You have two solutions in this particular case.

one way is to use single quotes within double quotes or vice versa.

let text = "Mars, also called 'The Red planet' will be inhabited one day."

But, the other better way is to use escape sequences or escape characters. You can use a backslash followed by double or single quotations.

let text = "Mars, also called \"The Red planet\" will be inhabited one day."

You can use the escape character and the backslash in many other situations.

You can the code part in the console.log() statement and see what the output looks like.

There are more uses of escape characters in JavaScript.

  • \b — backspace
  • \f — form feed
  • \v — vertical tab
  • \xXX — hexadecimal escape sequence (e.g. \x41 for the letter “A”)
  • \uXXXX — Unicode escape sequence (e.g. \u00A9 for the copyright symbol ©)

Adding long strings

What if you have a string with a lot of characters? If you include such a string within one line of your code, it can be difficult for another developer to read your code.

You can avoid adding long strings using the backslash character within the quotations.

const longString = "This is a very long string that goes on and on, \
and it can be difficult to read and work in your code. \
But you can use a backslash to break it up into multiple lines, \
like this. This makes your code easier to read and work with, \
especially when working with long strings like this on a regular basis.";

However, the use of a backslash(\) is not recommended because some browsers may not support it for this use case.

A much better way is to use the + operator ( string concatenation).

const longString = "This is a very long string that goes on and on, " +
"and it can be difficult to read and work in your code. " +
"But you can use the plus (+) operator to concatenate " +
"multiple strings into one, like this. This makes your " +
"code easier to read and work with, especially when " +
"working with long strings like this on a regular basis.";

Template literals

Earlier, we created a string using backticks ( backquotes). In other words, we use template literals in Javascript to create a string.

Using template literals offers some advantages. Let’s see what these are.

When we create a string with javascript template literals, you can use a variable or expression with the string. This is called string interpolation in JavaScript.

const name = "John";
const age = 30;
const profession = "developer";
console.log(`My name is ${name}, I'm ${age} years old and I work as a ${profession}.`);

You can also use expressions.

const x = 10;
const y = 5;
console.log(`The sum of ${x} and ${y} is ${x + y}.`);//The sum of 10 and 5 is 15.

Using expressions in template literals can make it easier to construct complex strings and avoid the need for concatenation or string concatenation functions like concat().

Template literals can also be used to create multi-line strings in JavaScript.

let str = `I am  
a
multi-line
string created
with template literal`;

console.log( str);
/** output will be like this
"I am a
multi-line
string created
with template literal"
**/

Accessing characters in a string

You can access individual characters in two ways:

  1. Use the built-in method charAt().
let str = "developer";
str.charAt( 5 );

2. Use bracket notation

let str = "developer";
console.log(str[5]); // "o"

Note: when you see this array-like syntax, you will have a temptation to change the value of any character as follows:

str[0] = "D";
console.log(str);

However, The output will be “developer”, and NOT “Developer”.

Why?

This is because Strings in Javascript are immutable. You can not change it once you created it.

Note: If you really in need of changing a character in a string you can use the slice() method as follows

let str = "developer";
str = "D" + str.slice(1);
console.log(str);

This will output “Developer” because a new string has been created with the desired changes.

Immutable strings can be beneficial in some ways because they prevent unexpected changes to the original string and make it easier to reason about the code.

However, it’s important to keep in mind that creating new strings can also be inefficient in terms of memory usage and performance.

Therefore, it’s important to use string operations judiciously.

String concatenation

Earlier I mentioned string concatenation when we talk about lengthy strings in your code.

Let’s talk more about string concatenation

If you have two or more string variables, you can concatenate these strings into one string.

const greeting = "Good morning, ";
const question = "How can I help you ?";
const welcome = greeting + question;
console.log( welcome );//Good morning, How can I help you ?

If you also add numbers to a string. The output will be a string

const userId = "admin" + 1278; 
console.log( userId ) //admin1278;

JavaScript uses a process called type coercion ( String coercion ) to convert one type of value to another type when necessary. In the case of adding a number to a string, JavaScript will convert the number to a string and then concatenate it with the other string.

Comparing strings

Now, let’s talk about comparing strings

You can use <, > , >=, <=. ==. === operators to compare strings.

These operators compare Unicode character codes/ASCII Character Codes that represent the character.

Because the following statement will return false as “a” is less than the character code for “b”.

console.log("apple" > "banana");

But, console.log("apple" > "Banana") will return true because “a" is greater than the character code for "B".

The following table shows the condition that applies when comparing strings.

Equality( == ) and strict equality ( === )

Now, let’s look into an interesting behavior with Equality operators.

console.log( “10” == 10 ) //true

This is because the “==” operator compares only the values of two strings for equality, but it does not compare their types.

On the other hand, the “===” operator compares the values of two strings and their data types. This means that if two strings have the same value, but different data types, the “===” operator will return false.

console.log("10" === 10); // false

Note that Inequality ( !=) and strict Inequality (!== ) has the same behavior.

Unexpected behavior when comparing string objects

As you learned above, when you compare two primitive strings using the === operator, JavaScript compares the values of the strings themselves.

However, when you compare a primitive string to a string object using ===, JavaScript first coerces the string object to a primitive string using the valueOf() method, and then compares the two primitive strings.

This can lead to unexpected results if you’re not aware of how the comparison works.

let string1 = "developer";
let string2 = new String("developer");
console.log(string1 === string2); // Output: false

If you do need to compare a primitive string to a string object, you can use the toString() method to explicitly convert the string object to a primitive string before comparing.

also, consider the following examples

let string1 = new String("developer");
let string2 = new String("developer");
console.log( string1 == string2 )//output false
onsole.log( string1 === string2 )//output false

As mentioned before, here also, you can use the toString() method to explicit conversion on the string objects before comparing.

But, in general, avoid creating strings as string objects, and use string literals whenever possible.

Javascript String methods

Javascript String object has a lot of built-in methods for you to work with strings.

Some of the most useful methods that you will encounter are listed below.

You can learn about how to use the substring() methods in this post.

Wrapping up

In this guide to javascript string, you learn about how to create a javascript string using string literals, template literals, and string constructors.

You learned which one is recommended and which one to avoid. We also talk about getting the length of a string, accessing the character in a string, string concatenation, and so on.

I hope this comprehensive guide will help you to become a competitive JavaScript developer.

--

--