JS Create String

How to Create a String in JavaScript

In JavaScript, strings are used to represent and manipulate text. There are several ways to create strings, each with its own specific use cases and advantages. Understanding these methods is essential for effective JavaScript development.


1. Create Strings Using Literals (Recommended)

The most common and recommended way to create a string in JavaScript is by using string literals. You can use either single quotes ('...') or double quotes ("...").

While both work exactly the same way, it is a best practice to choose one style and remain consistent throughout your codebase.

String Literals Example:

// Using Single Quote
let s1 = 'abcd';
console.log(s1);

// Using Double Quote let s2 = "abcd"; console.log(s2);


2. Create Strings Using Template Literals (String Interpolation)

Introduced in ES6, Template Literals use backticks (`...`) instead of regular quotes.

Template literals are highly versatile because they allow for string interpolation. This means you can easily embed variables and expressions directly inside the string using the ${...} syntax, making your code much more readable.

Template Literals Example:

let s1 = 'IntricateDevo';
let s2 = `You are learning from ${s1}`;

console.log(s2);


3. Multiline Strings (ES6 and later)

Before ES6, creating a string that spans multiple lines required using the newline character (\n) or string concatenation.

Now, you can create a multiline string effortlessly using backticks (`) with template literals. The backticks allow the string to span across multiple lines naturally, preserving the line breaks exactly as they appear in the code.

Multiline Strings Example:

let s = `
    This is a
    multiline
    string`;

console.log(s);


4. Creating an Empty String

Sometimes you need to initialize a variable with a string type before adding content to it later. You can create an empty string by assigning either single or double quotes with absolutely no characters in between.

Empty String Example:

let s1 = '';
let s2 = "";

console.log(s1); // Prints a blank line console.log(s2); // Prints a blank line


5. Create Strings Using the Constructor (Not Recommended)

You can also create a string using the new String() constructor.

However, this method creates a String object instead of a primitive string type. It is generally not recommended because it can slow down execution speed and cause unexpected, buggy behavior when comparing strings using the strict equality operator (===).

String Constructor Example:

let primitiveString = 'abcd';
let objectString = new String('abcd');

console.log(objectString); // Outputs: [String: 'abcd']

// Unexpected comparison behavior: console.log(primitiveString === objectString); // false, because one is a string and the other is an object


Exercise

?

Which syntax allows you to embed variables directly inside a string and easily span multiple lines?