JavaScript strings
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:
console.log("I" + " " + "am" + " " + "learning!")
// I am learning!
We can also join strings using the concat()
method (a built-in command), by listing them out inside the brackets:
console.log(concat("I", " ", "am", " ", "learning!"))
// 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:
// our variables
const x = "This is a long piece of text from one source!"
const y = "This is a longer piece of text from another source!"
const z = "I don't know where this came from but it must be true!"
// this will output all text in the variables above
// each variable is separated by a space
console.log(concat(x, " ", y, " ", z)
We can then easily change the text in variables, rather than in the console.log
line of code!