Make Object Properties Private explanation

Make Object Properties Private explanation


Hey guys,
I passed this challage already but still dont really understand everthing.
I mean I already knwo that if I call “Car” with the “new keyword” it creates an object with the properties I created.
But when decelerate is assigned to the function like in the example, why I doesnt return “5”? Because I would think (it takes speed which is 10 and subtracts it by 5 ).
Thanks a lot. It would be also great if someone could explane what the whole code is doing, like from the top to the bottom but I am thankful for every help.

var Car = function() {
  // this is a private variable
  var speed = 10;

  // these are public methods
  this.accelerate = function(change) {
    speed += change;

  this.decelerate = function() {
    speed -= 5;

  this.getSpeed = function() {
    return speed;

var myCar = new Car();

Console gives me “undefined” when I call it!


You’re console.logging the result of a method that doesn’t explicitly return anything (so returns undefined). Try making use of your getSpeed method


Hey @Renefe,
to understand what the code is doing, you need to be familiar with Object Oriented Programming.
Also, like @Swoodend mentioned, calling the decelerate method associated with the Car class returns undefined because it does not have a return statement.

What the code you asked about does is define a Class (Object) named Car. Every car instance will have a speed property (variable) that’s unique. Meaning, each Car object will have it’s own speed variable and won’t share it with other Car objects. Later in the code are three methods attached to the Car class (as can be seen by the this.accelerate and this.decelerate and so on). Each of these methods is a function the does some logic on the object’s property, speed.

Notice how only getSpeed returns the speed. If you were to call it, you would get the current speed of the object you are calling it on.

var myCar = new Car();
console.log(myCar.getSpeed());  <----- Will print to the screen the value 10


I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.