Strings
This YouTube video was created by Steve Griffith.
This Scrimba screencast was created by Dylan C. Israel.
String Literals
In JavaScript, a string literal is any number characters (letters, numbers or special characters) surrounded by a set of quotes (either single or double).
const animal = 'dog'
const phone = '555-555-5555'
Note
Both single '
and double "
quotes can be used for strings. It is a preference for which one to use, but is it best to stay consistent.
Concatenation Operator
The term concatenation refers to the combining of two or more strings together. In JavaScript, this is accomplished by use of the plus sign (+
) . Concatenation can be used with string literals, numbers and variables.
const greeting = 'Hello, ' + 'world'
const pet = 'dogs'
const number = 3
console.log('I have ' + number + ' ' + pet + '.')
When concatenating, JavaScript will attempt to convert all values to strings. Furthermore, because the plus sign (+
) is also use for addition, this can cause unexpected results when working with strings and numbers.
const add = 2 + 1 // 3
const cat = '2' + 1 // 21
Concatenation Method
The concat()
method can be used to concatenate strings to the calling string.
const greeting = 'Hello'
const name = 'Ted'
greeting.concat(' ', name) // Hello Ted
Template Literals
This YouTube video was created by Steve Griffith.
This Scrimba screencast was created by Dylan C. Israel.
The template literal is a syntax for string literal that allows for embedded expressions and multi-line support. To create a template literal the backtick (`
) is used to surrounded the string literal and any expressions.
const greeting = `Hello, World`
Template Literal Placeholders
Template literal can contain placeholders (${expression}
) which are used to embed contain an expressions into a string. Expressions can include variables, formulas or functions.
const name = 'Ted'
const game = `Have you met ${name}?`
const a = 5
const b = 3
const product = `The product of a and b is ${a * b}`