In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string.
To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.
let myPet = ‘seahorse’;console.log(‘My favorite animal is the ‘ + myPet + ‘.’); // My favorite animal is the seahorse.
Above, we created a variable myPet and assigned it ?seahorse?. On the second line, we concatenated three strings: ?My favorite animal is the ? (include the space at the end), the variable, and the period. The result is ?My favorite animal is the seahorse.?
Using a single quote or a double quote doesn?t matter as long as your opening and closing quotes are the same. The one time it matters if you are using a word that has an apostrophe like ?I?m?. It will be easier to use a double quote instead of using an escape character.
Another thing to take note of is when concatenating numbers and strings. When you concatenate a number with a string, the number becomes a string.
let myAge = 85;console.log(“I am ” + myAge + ” years old.”);// I am 85 years old.
Another way to include a variable to a string is through String Interpolation. In JavaScript, you can insert or interpolate variables into strings using template literals. Here is an example of a template literal using our first example:
let myPet = ‘seahorse’;console.log(`My favorite animal is the ${myPet}.`);
Template literals are enclosed in backticks. You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation. The difference is, the interpolation example is much easier to read.
If you want to read more JavaScript basics articles, you can check out my recent ones here: