1

I am new to JavaScript. I have the following code in JavaScript:

function Person(first_name, last_name) {
    this.first_name = first_name;
    this.last_name = last_name;

    this.displayName = function() {
        console.log(`Name: ${this.first_name} ${this.last_name}`);
    };
}

let john = new Person('John', 'Reid');
john.displayName();

The output of this code is: "Name: John Reid"

I want to understand how this works? What is the role $ is playing in this code? In this part of JavaScript language specification or some other library at work here?

Thanks

rsp
  • 537
  • 2
  • 13
  • 3
    They're called template literals or template strings. Read here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – j08691 Jun 08 '20 at 17:13
  • its a normal javascript feature that allows you to render javascript code directly into your string – bill.gates Jun 08 '20 at 17:15
  • If you're learning JavaScript from a book or some web resource, make sure it's up-to-date. Template literals are a relatively recent addition to the language. A learning resource more than 5 years old probably won't mention them. – Pointy Jun 08 '20 at 17:15
  • You should starts with ` but ends with ' – daniel Jun 08 '20 at 17:17
  • 1
    @daniel that is not correct – Pointy Jun 08 '20 at 17:18
  • @daniel What? Noooo – j08691 Jun 08 '20 at 17:25
  • Oh, maybe i mix up another programming language... – daniel Jun 08 '20 at 17:26
  • Does this answer your question? [Usage of the backtick character (\`) in JavaScript](https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript) – ASDFGerte Jun 08 '20 at 17:29

2 Answers2

1

${} is used for string interpolation. The variables are added to a string using ${} and plain text is added normally. You also can use the + symbol to interpolate strings

"Name: " + this.first_name + " " + this.last_name

but it is cleaner if you use the first option.

sibabrat swain
  • 1,277
  • 8
  • 20
mgm793
  • 1,968
  • 15
  • 23
1

This is pure javascript. No javascript library used here.

The new keyword is used in javascript to create an object from any function. You have created the instance and then you are calling the displayName property which is itself a function and show the output as you have used console.log().

 console.log(`Name: ${this.first_name} ${this.last_name}`);

is same as

 console.log("Name: " +  this.first_name  + " " + this.last_name);

In the first one, you are achieving the same output but using template literals.

They were called "template strings" and introduced in ES2015 specification. Template literals (Template strings)

And the second one is the traditional concatenation.

sibabrat swain
  • 1,277
  • 8
  • 20