Strings in JavaScript

Strings in JavaScript are used to store a sequence of characters or text. They are also used to manipulate text. Strings are stored inside quotes. You can store them in single or double-quotes.


// double quotes
var name = "John Doe";
//single quotes
var gender = "male";
console.log("Name: ", name);
console.log("Gender: ", gender);


Name: John Doe
Gender: male

You can also use quotes inside strings.


var str1 = '"JavaScript" is one of the popular programming languages.';
var str2 = "It's easy to learn.";
console.log(str1, str2);


“JavaScript” is one of the popular programming languages. It’s easy to learn.

Strings as Objects:

You can create strings in JavaScript using literals. But, you can also create strings defined as strings by using the keyword “new”.


var language = new String("JavaScript");


If you create a string using literal then the type will be a string. But, if you create string defined as object then the type will object.
Creating strings using objects is not a good practice. It affects the execution of code. Code execution will be slow. So, create strings using literals.

Long Code Line breaking:

For readability purposes, it’s good to break long code lines. If the string is long and you break it by pressing enter then JavaScript will give the error. There are several ways to break long code lines.

  1. You can break the long code line by breaking text string using a single backslash. But using this method for long code lines is not good practice. It is not supported by some browsers.
  2. You can break the long code line by breaking a string using string addition.
  3. If you want to break the single long code line into multiple lines. You can break it after the operator.
  4. Using template literals you can break the long string.

You can refer code below for above long code lines breaking methods.


<!DOCTYPE html>
<html lang="en">

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Strings in JavaScript</title>

  <div id="demo1"></div>
  <div id="demo2"></div>
  <div id="demo3"></div>
  <div id="demo4"></div>
    document.getElementById("demo1").innerHTML = "Hello \
    document.getElementById("demo2").innerHTML = "Hello " +
    document.getElementById("demo3").innerHTML =
      "Hello World.";
    document.getElementById("demo4").innerHTML = `Hello



Hello World.
Hello World.
Hello World.
Hello World.


From this tutorial, you learned how to create strings in JavaScript. You also learned how to break long lines of code or string.

Additional Links:

String methods and properties in JavaScript

Variables in JavaScript

Loops in JavaScript

Notify of
Inline Feedbacks
View all comments