Here are four ways to combine strings in JavaScript. My favorite way is using Template Strings. Why? Because it’s more readable, no backslash to escape quotes, no awkward empty space separator, and no more messy plus operators 👏
const icon = '👋';
// Template Strings
`hi ${icon}`;
// join() Method
['hi', icon].join(' ');
// Concat() Method
''.concat('hi ', icon);
// + Operator
'hi ' + icon;
// RESULT
// hi 👋
If you come from another language, such as Ruby, you will be familiar with the term string interpolation. That’s exactly what template strings is trying to achieve. It’s a simple way to include expressions in your string creation which is readable and concise.
const name = 'samantha';
const country = '🇨🇦';
Before template strings, this would be the result of my string 😫
"Hi, I'm " + name + "and I'm from " + country;
☝️ Did you catch my mistake? I’m missing a space 😫. And that’s a super common issue when concatenating strings.
// Hi, I'm samanthaand I'm from 🇨🇦
With template strings, this is resolved. You write exactly how you want your string to appear. So it’s very easy to spot if a space is missing. Super readable now, yay! 👏
`Hi, I'm ${name} and I'm from ${country}`;
#web-development #javascript-tips #javascript