Private Property - No Entry!

Here's something pretty cool; properties the way we've been declaring them in objects are public, they can be accessed by any function, but we can also create private properties. Here's a simple example:

function Car(brand,model,year,balance) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    // create a private property
    var balance = balance;
}

var myCar = new Car("Ford","Model T",1917,5600);

// out test output
console.log("I own a " + myCar.model + " on which I owe " + myCar.balance);

When we run this we get I own a Model T on which I owe undefined. We don't have access to the private property so it doesn't print. By adding a method we're able to access the data, like in the example below.

function Car(brand,model,year,balance) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    // create a private property
    var balance = balance;
    // add a method to make the private property available publicly
    this.displayBalance = function() {
        return balance;
    }
}

var myCar = new Car("Ford","Model T",1917,5600);

// out test output
console.log("I own a " + myCar.model + " on which I owe " + myCar.balance);

//our test output using the displayBalance method
var myBalance = myCar.displayBalance();
console.log("I own a " + myCar.model + " on which I owe " + myBalance);