Lesson Weekend

We've done a lot with numbers, but there's more to this world than just math. Let's look at words.

> "Hello world!";
"Hello world!"

The stuff inside the quotes is called a string. Strings can include letters, punctuation, and even numbers.

> "5674";
"5674"
> "!?&";
"!?&"
> "Strings are wild! ;)";
"Strings are wild! ;)"

What happens if we don't surround our string with quotes?

> hello;
x Uncaught ReferenceError: hello is not defined (...)

This doesn't work because JavaScript doesn't know what hello means when it's not a string. It looks to see if it's a variable or something similar, and then doesn't find it defined anywhere.

We can set variables equal to strings:

> const myString = "Strings can contain characters like @, $, and %.";
undefined

If you want to put a quote inside a string, you have two options. Here's the first:

> "Quoth the raven, \"Nevermore.\"";
"Quoth the raven, "Nevermore.""

The \\ around either side of the text above is called an escape. It tells JavaScript that the " that comes right after it is not the end of the string, but just a character inside the string.

You can also use single quotes:

> '"Programming is fun!", she exclaimed.';
""Programming is fun!", she exclaimed."

JavaScript generally doesn't care if you use single or double quotes to indicate a string. If you have a lot of double quotes within the string, using single quotes to indicate the string saves you from having to escape all of the double quotes inside.

Finally, note that we are still using semicolons at the end of each line. By doing so, we can be explicit about where a piece of code terminates (at the end of a line) instead of expecting JavaScript to automatically do it for us.

Terminology


  • String: a JavaScript data type that represents the exact text of whatever is enclosed in the quotes

Examples


"Strings can contain letters, numbers like 1, 14.5, and 5784329, and characters like @, $, and %."

You can assign variables to strings:

> const myString = "Strings can contain characters like @, $, and %.";

Include quotes in strings by either escaping them with \\, or by using single quotes outside:

"Quoth the raven, \"Nevermore.\"";

You can use either single quotes ' ' or double quotes " " around your strings, as long as the start and end quote marks match.

'This is a string surrounded by single quotes.';
"This is a string surrounded by double quotes.";

Lesson 9 of 27
Last updated April 7, 2021