-3

Hello Stack Overflow Community, Can anyone explain me this piece of code ?

// Create a function that returns HTML with data
const myBox = (title, description) =>
`<div class="box"><h3>${title}</h3><div>${description}</div></div>`;

I understand the basic functionality of it, but I cannot understand the `` that is around the <div> and the ${title} and ${description} part.

I would be really glad if anyone could help me. Thanks.

Ahmed Can Unbay
  • 2,694
  • 2
  • 16
  • 33
Bruno MS
  • 1
  • 1
  • This function returns a `template string`. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/template_strings – Philip Sep 09 '17 at 23:11

3 Answers3

1

Those are called Template Literals. They allow you have multi-line strings and allows you insert expressions using ${expression} and the result of that expression will be inserted into that point in the string.

samfundev
  • 78
  • 1
  • 6
1

it is Template Literals, it is not related with Arrow function.

As the example, in MDN document shown:

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
which equals to
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
AlexLuo
  • 458
  • 1
  • 4
  • 12
0

There are few things going on here.

Here are some docs on Arrow functions. In the docs you will see how they will return the value automatically if there are is no body block. The return statement needs to be included if the body blocks are included like so.

var func = x => x * x;                  
// concise syntax, implied "return"

var func = (x, y) => { return x + y; }; 
// with block body, explicit "return" needed

Now, what is being returned here?

`<div class="box"><h3>${title}</h3><div>${description}</div></div>`;

This is a string literal which everyone is talking about in the other answers. which I believe I don't need to talk more about.

So this code is a function that returns a string. I'm guessing this is React code or something like it. It will call this function get the string and create DOM elements with what is returned.

Michael Warner
  • 3,879
  • 3
  • 21
  • 45