Getters and Setters

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Getters and Setters

When you access an object’s property, you get the value it contains.

const object = {
  property: 'value'
}

console.log(object.property) // value

Getters let you run a function when accessing a property. They begin with a get keyword, followed by a normal function. Here’s what it looks like:

const object = {
  get property () {/* ... */}
}

The value you obtain will be the value the getter returns.

const object = {
  get property () { return 'Hello World!' }
}

console.log(object.property) // Hello World!

When used in an Object Oriented Programming context, getters can be privileged methods that return a private variable. We’ll use the Car example to illustrate this point.

First, we’ll create a getter function. We’ll call this function fuel. In this fuel getter, we will return the private variable, fuel.

function Car () {
  const fuel = 50

  return {
    get fuel () { return fuel }
  }
}

Car instances should now be able to get fuel (the private variable) with the fuel getter.

const car = new Car()
console.log(car.fuel) // 50
Getting `fuel` with a getter function.

If you console.log a Car instance, you should see a fuel property. But the value of this fuel property is hidden behind (...) in Chrome Devtools. If you’re using Firefox, you’ll see >> instead of (...).

fuel property on Chrome

If you hover over the (...) or >> symbol, you’ll see “invoke getter”.

Invoke Getter on Firefox

Although users can get fuel (the private variable) with fuel (the getter function), they cannot change fuel (the private variable) and break our Car implementation.

const car = new Car()
car.fuel = 5000 // This line does nothing
console.log(car.fuel) // fuel remains at 50
Value remains at 50

We can prove that fuel (the getter) was called if we create a console.log statement.

function Car () {
  const fuel = 50

  return {
    get fuel () {
      console.log('Getting amount of fuel')
      return fuel
    }
  }
}

const car = new Car()
car.fuel = 5000 // This line does nothing
console.log(car.fuel) // fuel remains at 50
Shows the log statement. `fuel` remains at 50.

If we want to let users change fuel with car.fuel, we need a Setter function. (More on this later).

Why use Getters?

Two reasons: Convenience and memorability.

Which would you rather use? car.fuel or car.getFuel()? Most likely, you’d choose car.fuel because it’s shorter and easier to remember.

It’s also easier to use car.fuel because we’re used to getting values from objects this way.

Setters

Setters are like getters. Except they let you set values. To use setters, you write a set keyword, followed by a function. The set function takes in one variable.

let string = 'Hello World!'
const object = {
  set property (newValue) { string = newValue }
}

object.property = 'Good Morning!'
console.log(string) // Good Morning!

When used in an Object Oriented Programming context, setters can be used as privileged methods to modify private variables. Again, we’ll use the Car example to illustrate this point.

First, we’ll create a fuel setter function.

function Car () {
  let fuel = 50

  return {
    get fuel () {/* ... */}
    set fuel (amount) {/* ... */}
  }
}

This fuel (the setter) should modify fuel (the private variable).

function Car () {
  let fuel = 50

  return {
    // ...
    set fuel (amount) {
      fuel = amount
    }
  }
}

The fuel’s tank maximum capacity is 100 litres. If the user pours in an excessive amount, we reset the tank back to 100 litres.

function Car () {
  let fuel = 50

  return {
    // ...
    set fuel (amount) {
      fuel = amount
      if (fuel > 100) {
        console.log('Fuel Tank Capacity is 100 litres. Pouring away excess fuel')
        fuel = 100
      }
    }
  }
}

We can now set the fuel (the private variable) using the fuel property. Any excess fuel will be poured away.

const car = new Car()
car.fuel = 5000
Pouring away extra fuel.

We should also be able to check the amount of fuel with the fuel getter.

const car = new Car()
car.fuel = 5000
console.log(car.fuel)
Logs the amount of fuel. Shows 100.

The addFuel method

We still want an addFuel method because it lets users add fuel into the car.

function Car () {
  let fuel = 50

  return {
    // ...
    addFuel (amount) {/* ... */}
  }
}

addFuel is much easier to write now. We can delegate the task to the fuel setter method.

function Car () {
  let fuel = 50

  return {
    // ...
    // this.fuel uses the fuel setter method
    addFuel (amount) { this.fuel = fuel + amount }
  }
}

We can now add fuel into the car.

const car = new Car()
car.addFuel(30)
console.log(car.fuel) // 80
Adds fuel into the car.

Getters and Setters in other flavours

Constructor Syntax

Getters and Setters must be written inside an object. You can add Getters and Setters to a constructor via Object.assign

function Car () {
  let fuel = 50

  Object.assign(this, {
    get fuel () {/* ... */}
    set fuel (amount) {/* ... */}
  })
}

You can also use getters and setters in the prototype.

function Car () {
  // ...
}

Object.assign(Car.prototype, {
  get property () {/* ... */}
  set property (value) {/* ... */}
})

Class Syntax

You can write Getters and Setters as normal methods inside a class syntax. Getters and Setters defined this way will automatically be added to the Prototype.

class Car {
  #fuel = 50
  get fuel () { /* ... */ }
  set fuel (amount) { /* ... */ }
}

OLOO

You can write Getters and Setters as normal methods inside OLOO.

const Car = {
  init () {
    let fuel = 50
    return {
      get fuel () {/* ... */}
      set fuel (amount) {/* ... */}
    }
  }
}

That’s it!