Skip to content
davidbarna edited this page Apr 27, 2018 · 2 revisions

Strings

Primitive vs Objects

Types

String instances hold a primitive string accessible thanks to the String.prototype.valueOf() function.

typeof '5' // "string"
typeof new String('5') // "object"
typeof new String('5').valueOf() // "string"

Comparison

When an object is compared to a string, String.prototype.valueOf() is called internally to make the comparison.

const a = new String('foo')
const b = new String('foo')

a == b // false as a and b are type Object and reference different objects
a == 'foo' // true as the Object (a) is converted to String 'foo' before comparison

Template strings (ES6)

Template literals are string literals allowing embedded expressions.

You can use multi-line strings and string interpolation features with them.

Template literals are enclosed by the backtick `` , not'`or`"`

MDN // Template literals

Template literals are a different syntax, not a different primitive of object.

;`\`` === '`' // true
;`\`` === '`' // true
;`'` === "'" // true
;`"` === '"' // true

Multi-line strings

Any new line characters inserted in the source are part of the template literal.

Regular string:

//prettier-ignore
const str = 'string text line 1\n' +
'string text line 2\n' +
'string text line 3'
//prettier-ignore
const str = "string text line 1\n" +
"string text line 2\n" +
"string text line 3"

Template string:

const str = `string text line 1
string text line 2
string text line 3`

Multi-line strings

The result string is exactly the same.

const text1 = 'string text line 1\n' + 'string text line 2'

const text2 = `string text line 1
string text line 2`

text1 === text2 // true

Expression interpolation

In order to embed expressions within normal strings, you must enclosed them inside a ${}

const a = 5
const b = 10
const text1 = 'Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'
const text2 = `Fifteen is ${a + b} and\nnot ${2 * a + b}.`

text1 === text2 // true
console.log(text1)
// "Fifteen is 15 and
// not 20."

Further Info

exploringjs.com // Template literals