0

So I've been working through Freecodecamp's courses. I've come across this piece of code in an example:

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

In this situation, why has "sayHello" been made a function? Why not simply write:

    sayHello: `Hello! My name is ${this.name}.`

Wouldn't that return the same thing?

Apologies for any common sense mistakes here, I'm pretty new to all of this.

Tack00
  • 1
  • Well it's absurd question in a way you asked why `sayHello` property is a function and not a string? You could've asked the same thing for "why is `sayHello` simply not written as `sayHello: 5`?". You get it? You didn't asked anything specific about it! I don't know if you have trouble with either a string, function or `this`? For string & function in this case: string can't be called, its value can only be accessed while function can also be called. `this` is a longer topic: [this Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – Aleksandar Jan 01 '23 at 23:16
  • So, for anyone who might stumble upon this one day, if it helps, I figured it out. It turns out that the function part of the code is what activates the template literal. If I weren't to include the function, the string data returned would be "Hello! My name is ${this.name}." This obviously wouldn't be what I want. – Tack00 Jan 05 '23 at 05:41

0 Answers0