1

Code looks like this

let car = {
    make: "bmw",
    model: "520",
    isStarted: false,
    start: function() {
        isStarted = true
    },
    drive: function() {
        if (isStarted) {
            console.log("I am driving away....")
        } else {
            console.log("I am still false")
        }
    }
}

car.start();
car.drive();

I read that since isStarted is part of an object i need to use this to tell JavaScript which isStarted i am thinking of. But car.start() executes like it knows it is isStarted from the object without needing this keyword, unless

....
start: function() {
    if(!isStarted) {
       isStarted = true
    }
}
....

isStarted is placed inside if and now i need if (this.isStarted) because it throws undefiend.

J.DoeDoeJ
  • 13
  • 5
  • You should use this - alone isStarted may be undefined so it always is false. – Zydnar Feb 13 '20 at 10:18
  • In your `start()` function, `isStarted = true` does not throw an error because it creates a variable that holds the value. However, when you are attemtping to access `isStarted` in the `drive()` method, it will fail since it is not defined. – Terry Feb 13 '20 at 10:19
  • 1
    isStarted = true, is just creating a global variable. if you console.log(car.isStarted) you will see it still with the false value. – IWHKYB Feb 13 '20 at 10:19

1 Answers1

4

You need to address this in the start function, otherwise you create a global variable isStarted.

let car = {
    make: "bmw",
    model: "520",
    isStarted: false,
    start: function() {
        this.isStarted = true;
    },
    drive: function() {
        if (this.isStarted) {
            console.log("I am driving away....")
        } else {
            console.log("I am still false")
        }
    }
}

car.start();
car.drive();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    Thanks, i get why, `drive` executes because it finds the global `isStarted` that is set to `true` and not the one in object – J.DoeDoeJ Feb 13 '20 at 10:33