Egg laying exercise issues

I’m learning about the ‘this’ keyword and I like its usefulness. I’m having trouble w/ the basics of returning the code though.

const hen = { name: 'Helen', eggCount: 0, layAnEgg() { return (${this.eggCount++} ) } };

I think I’m incrementing incorrectly.

This is a syntax error. You can only use this with template literals. So you’ll want to add backticks around this expression.

As for the incrementing of eggCount in the layAnEgg method, should it return the number of eggs before the hen lays an egg or the number of eggs after the hen lays an egg. I would read up on the increment operator a little more.

It should add an egg. So it would be a post-fix increment. But that isn’t being accepted as a valid solution.

Edit: Or maybe I’m putting the ++ in the wrong place? eggCount++ when it should be something else?

Are you sure about this? Can you explain the difference between postfix and prefix increment. Are you testing your code? When you call layAnEgg for the first time, how many eggs does it return with postfix? How about with prefix?

Update: The reason prefix/postfix is important is because you are doing the incrementing in the return statement. If you did the incrementing first, outside of the return statement, then it wouldn’t matter.

I think this is probably something you can debug and figure out for yourself.

Here is the exercise. Should’ve posted this earlier.

Define an object called “hen”. It should have three properties:

  • name should be set to ‘Helen’
  • eggCount should be set to 0
  • layAnEgg should be a method which increments the value of eggCount by 1 and return the string “EGG”. You’ll need to use “this” property.

If layAnEgg() should return the string “EGG” then why are you returning this.eggCount? Shouldn’t you just be returning the string “EGG”? So pull this.eggCount++ out of the return statement onto a line of its own. In this case, it doesn’t matter whether you use the prefix or postfix increment because what you are returning doesn’t depend on the value of this.eggCount.

But it’s part of a template literal too though. It needs to be adding an egg and then post/return it to the user.

I’m just going by the instructions you posted above. There are two steps here:

  1. Increment the number of eggs by 1
  2. Return the string “EGG”

Two steps, two lines of code. You increment on the first line and return the string on the second line.

You can forget about template literals for now because they are not needed here. You can just return the string “EGG”.

Either way, I’m thinking too much about this lol.

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