JavaScript Strings

A string is a sequence of characters.

It can be also defined as a string literal, which is enclosed in quotes or double quotes:


'JavaScript';
'I love JavaScript';

I personally prefer single quotes all the time, and use double quotes only in HTML to define attributes.

You assign a string value to a variable like this:


let name = 'JavaScript';

You can determine the length of a string using the lengthproperty of it:


'JavaScript'.length;//10
let string = 'JavaScript';
string.length;//10

Example


let string = 'JavaScript';
console.log(string.length);

This is an empty string: ''. Its length property is 0:


''.length;//0

Two strings can be joined using the +operator:


'A' + 'String';

You can use the + operator to interpolate variables:


let string = "JavaScript";
'I love ' + string; //I love JavaScript

Example


let string = "JavaScript";
console.log('I love ' + string);

Another way to define strings is to use template literals, defined inside backticks. They are especially useful to make multiline strings much simpler.

With single or double quotes you can't define a multiline string easily: you'd need to use escaping characters.

Once a template literal is opened with the backtick, you just press enter to create a new line, with no special characters, and it's rendered as-is:


const string = `Hey
  this

  string
  is awesome!`;

Template literals are also great because they provide an easy way to interpolate variables and expressions into strings.

You do so by using the ${...}syntax:


const language = "JavaScript";
const string = `I love ${name}`; //I love JavaScript

Example


const language = "JavaScript";
const string = `I love ${name}`;
console.log(string);  //I love JavaScript

inside the ${}you can add anything, even expressions:


const string = `I love ${1 + 2 + 3}`;
const string2 = `I love ${foo() ? 'x' :'y'}`;