What is the syntax for using this to interpolate a string?


#1

The exercise is:

Calling a key outside of current scope - lesson

sayHello: () => {return 'Hello, my name is ${this.name}}',

Above is what I have

Below is what is expected, I think

'This is how you interpolate a variable like ${MyVariable}'

The error I am getting is unexpected token.

Any help would be appreciated.

I may be out for a couple of hours but I will look.

MDN: MDN documentation - already viewed

The above does not provide context for this problem.

I’m pursuing this path because they say if you spend large amounts of time on learning syntax, you will never forget…instead of just looking at the answers!


#2

this:

sayHello: () => {return 'Hello, my name is ${this.name}}',

is a good example why you shouldn’t put this code on a single line, if you would have done:

sayHello: () => {
    return 'Hello, my name is ${this.name}
}',

that you close your string to late. Not sure what the comma is doing there

also, string interpolation requires the string to be enclosed in back-ticks (grave accent), not in apostrophes or quotation marks.


#3
var person = {
  
 name: 'JP',
 age: 102,
 weekendAlarm: 'No alarms needed',
 weekAlarm: 'Alarm set at 7AM',
  hobbies: ['boardgames'],
  sayHello: () => { ///Do I need to move this to the bottom of the list?
    return `Hello, my name is ${this.name}`
  sayGoodbye(){return 'Goodbye!'}
    
};

Responding to your question, the comma is there because there is another key following the object. I have used backticks like you said but still the error says unexpected token.

I’m trying to figure out why it says unexpected token.

Any help would be appreciated - as I’m learning to error read for this example.


#4

arrow function (=>) is not suitable for method deceleration. See here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#Description

how to declare a method, both the es5 and es6 way are displayed on this page.

you forgot a } to close your sayHello method.

There are two ways which are common to use curly brackets:

method {

}

or:

method
{

}

i really recommend you to start using them. Build in some good habits. There is a reason these two approaches are the most common, they reduce the change of making mistakes with missing curly brackets. And if you do miss them, they are easier to find. If you handle a single standard, that is.


#5

sayHello: () => {return 'Hello my name is ${this.name}}


#6

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