var title = "We wish " + "to be friends"; console.log(title);
Result in the console:
> We wish to be friends
var welcome = "Come sit"; var direction = "by the hearth"; console.log(welcome + " " + direction); > Come sit by the hearth
Concatenating Things to Themselves
It’s not unusual to set a variable to a string, then later want to add another string to the existing content. With the += assignment operator, we can do just that:
var welcome = "Good "; var time = "evening"; welcome += time; console.log(welcome); > Good evening
Note that the value of the welcome variable will be permanently altered by this process.
Different Strokes: concat
concat method also joins together strings:
var oneDay = "One day I met "; var riddle = oneDay.concat("a man ","going to St. Ives."); console.log(riddle); > One day I met a man going to St. Ives.
Note that the spaces must still be included in the string components in order for them to reflected in the final string result. You could also start a
.concat method from nothing, joining new strings to it:
var riddle = "".concat("The man had ", "seven wives");
join method concatenates all the elements of an array into a string. If we have an array cats:
var cats = ['Artemis', 'Catbus', 'Duchess', 'Figaro', 'Kuroneko-sama', 'Scratchy']; var joinedNames = cats.join(); console.log(joinedNames); > "Artemis,Catbus,Duchess,Figaro,Kuroneko-sama,Scratchy"
.join automatically joins the elements together the comma separator used in the array itself. That behaviour can be changed to any separator you wish, including spaces:
var joinedNames = cats.join(' '); > "Artemis Catbus Duchess Figaro Kuroneko-sama Scratchy"
join() is significantly slower than the standard
+ operator, and should be avoided where possible.
var a = 10; var b = 20; console.log('Total is ' + a + b);
You might expect the result to be 30. Instead, you’ll find:
> Total is 1020
> Total is 10 > Total is 1020
We solve the problem by wrapping the parts we want to be added together first in parentheses:
console.log('Total is ' + (a + b));
The result is now what we expect:
> Total is 30
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.