JavaScript strings
// updated 2025-05-02 07:35
A String
in JavaScript consists of consecutive alphanumeric characters, which includes:
- letters
- digits (not to be confused with numbers)
- whitespace
- punctuation
- special characters
- emoji (even these!)
We also encapsulate strings with quotation marks (either with 'single quotes' or "double quotes").
A string can consist entirely of numeric characters but it does not make it a number: if we have two strings, 2
and 2
, and we add them together, they will become 22
, not 4
!
Concatenating strings
In the console, we can test the following using +
on a set of strings:
1console.log("I" + " " + "am" + " " + "learning!")
2// I am learning!
We can also join strings using the concat()
method (a built-in command), by listing them out inside the brackets:
1console.log(concat("I", " ", "am", " ", "learning!"))
2// I am learning!
String variables
So why was that important? Why couldn't we simply type "I am learning!"
?
Well, later on, when we wish to gather longer samples of text from different sources, we may wish to store them into different variables.
To create a string variable in JavaScript:
- we use the
const
keyword - followed by a space
- give the variable a name
- followed by a space, an equal sign, and another space
- place the string with the quotation marks
The concat()
method then allows us to effortlessly combine multiple variables together:
1// our variables
2const x = "This is a long piece of text from one source!"
3const y = "This is a longer piece of text from another source!"
4const z = "I don't know where this came from but it must be true!"
5
6// this will output all text in the variables above
7// each variable is separated by a space
8console.log(concat(x, " ", y, " ", z)
We can then easily change the text in variables, rather than in the console.log
line of code!