Concatenation in Javascript Demystifying various method in strings and inserting HTML code

I often get confused when passing HTML in JS variables/objects.

If I start with a relevant example:

var message = data.name.first+' '+data.name.last ;

My Point of confusion:

Are we interchangeably using the + sign?

In the above example I tried to add an image:

var message = data.name.first+''+data.name.last + '<br><img src="+data.picture.large+" alt="">';

But this actually didn’t work.

I also have seen a few code writers using {} brackets to do the same. Can we also discuss that

Can we discuss this, the best practice and usage of " ", '', + sign when to use how to insert strings and how to insert HTML code?

For string concatenation you should probably be using template literals, unless you have to support legacy browsers (in which case, bad luck).

So this:

var message = data.name.first+' '+data.name.last ;

Becomes:

const fullName = `${data.name.first} ${data.name.last}`;

Also, this:

var message = data.name.first+''+data.name.last + '<br><img src="+data.picture.large+" alt="">';

is a nightmare to read/maintain.

This is much cleaner:

const fullName = `${data.name.first} ${data.name.last}`;
const htmlSting = `
  <p>${fullName}<p>
  <img src="${data.picture.large}" alt="${fullName}">
`;
1 Like

its worth pointing out here that ‘legacy browsers’ includes any version of Internet Explorer.

1 Like

Yep, it’s still going.

image

4 Likes

If you have to support IE and write more than a handful of JavaScript, use Babel.

4 Likes

Yoou have given a spacebar after 2nd $ to give a real space on live webpage or that is a typo?

Typo. Sorry.