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 =' ' ;

My Point of confusion:

Are we interchangeably using the + sign?

In the above example I tried to add an image:

var message ='' + '<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 =' ' ;


const fullName = `${} ${}`;

Also, this:

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

is a nightmare to read/maintain.

This is much cleaner:

const fullName = `${} ${}`;
const htmlSting = `
  <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.



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


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

Typo. Sorry.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.