Why the template literals not working?

  **Your code so far**

function Bird() {
let weight = 15;

this.getWeight = () => {return `${weight}`} //working
this.getWeight = function(){
  `${weight}`
  } //not working
}
//why ??
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

Challenge: Use Closure to Protect Properties Within an Object from Being Modified Externally

Link to the challenge:

It’s not a problem with template literals, your second function has no return statement.

You could simplify the first, by the way (because it’s a one-liner):

this.getWeight = () => `${weight}`

Right I see, I didn’t check the challenge. Both of your functions should actually fail.

It wants you to return the value of weight, which is a number. When you use a template literal, you’re converting the Number 15 into a String '15', that’s why the tests fail.

1 Like

Yep , Correct answer .

What would be the point of using a template literal here anyway if you don’t mind me asking?

I did it , just for fun.

Well, you did learn something, string literals are in fact (surprise, surprise) strings. As a rule of thumb, you should never change the data type unless you need to. If the return was used for some math you might end up with unexpected results (like string concatenation).

function Bird(weight) {
  let _weight = weight;
  this.getWeight = () => { return `${_weight}` }
}

let ducky = new Bird(15);
console.log(typeof ducky.getWeight()) // string
console.log(15 + ducky.getWeight()) // 1515

The test has a strict equals check so the type must match and the regex used won’t match on your code either. Experimenting is fine, just know a lot of challenges might break if you provide them with unexpected code.

1 Like

I agree

Totally agree

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