The method toggleCheckOutStatus()

I have two questions about the method toggleCheckOutStatus() :

    this._isCheckedOut = !this._isCheckedOut;

1 / I noticed that this other writing also works (isCheckedOut replaces _isCheckedOut to the right of the equality):

    this._isCheckedOut = !this.isCheckedOut;

I don’t understand why the result is correct too ?

2 / but if we remove the ‘_’ from the _isCheckedOut , which is on the left ( this.isCheckedOut = !this.isCheckedOut;), it doesn’t work anymore…
Could you explain to me why please?
Thank you !

Hi there.

It’s difficult to say for certain, without a link to the exercise/project that you’re attempting.

Still, we can take a guess. :slight_smile:

I presume this is because your object, whatever it is, contains a getter for isCheckedOut. What I mean is that, somewhere, you’ve got some code which looks like this:

const someObj = {
    get isCheckedOut() {
        return this._isCheckedOut;

The right-hand side of your assignment, !this.isCheckedOut, gets the value of the .isCheckedOut property and returns the opposite by applying the logical not operator.

Presumably, the object has a property of ._isCheckedOut. It likely doesn’t have a property of .isCheckedOut, and I’m guessing you don’t have a setter method with that name either. As a result, this.isCheckedOut does not exist (because it’s not a valid property of the object nor a method of the object).

That’s what I think might be happening, but if you can point me at the exercise I can check and make sure. :slight_smile:

Thanks for taking time to respond to me :slight_smile: !
This is part of the exercise “building a library”, at the end of the chapter 9 " classes"
Here is an excerpt from my code:

Media class {
constructor (title) {
this._title = title;
this._isCheckedOut = false;
this._ratings = ;
get title () {return this._title};
get isCheckedOut () {return this._isCheckedOut};
set isCheckedOut (newIsCheckedOut) {this._isCheckedOut = newIsCheckedOut};
get ratings () {return this._ratings};

toggleCheckOutStatus () {
this.isCheckedOut =! this._isCheckedOut;

  • Thank you for your explanation on the first part that I understood.
    Finally which is the most correct writing for the right part of equality: without the “underscore” (which comes from the getter, if I’m not mistaken ) or with “underscore” (I think which is the property of the object recovered directly) ?

  • for the second question (about the first part of equality), there is a setter in the Media class, but I realize that I had made a typo in the name of this._isCheckedOut, so it’s like there isn’t indeed :wink:
    This error rectified, whether I put “underscore” or not in front of isCheckedOut, it works correctly. Is it correct to say that this._isCHeckedOut will directly update the property of the Media class and that this.isCheckedOut will call the setter who will do it?
    which is more correct?

Many thanks !!!