Skip to content

JavaScript getter/setters (S|Get keyword) #49

Open
@jenbutongit

Description

@jenbutongit

👋 hey, this is a great repo/cheatsheet, thanks for this!

A couple points on your get/set examples, in short, they are confusing when compared with each other and conflicts with OO principles.
"Accesses data immediately (i.e. shorthand getter of internal data)."

// Get
function getFruitCount() {
  return this.fruits.length
}

this suggests that getFruitCount is part of either a class or object, which has the property fruits with type array (or other iterable).

const bowl = {
  fruits: ['apple', 'orange', 'pear'],
  getFruitCount() { this.fruits.length },
  get fruitCount() { this.fruits.length }
}

with the example above to get the number of fruits in the bowl, you can do either bowl.getFruitCount() or bowl.fruitCount. If you find you are using getFruitCount often in your code, or you are passing it into another function, it can get unreadable/extraneous quite quickly.

 throw new Error(`Not enough ${bowl.getFruitCount()}`);
 // vs
 throw new Error(`Not enough ${bowl.fruitCount}`);
// Set
let fruits = 0

function setFruits(nextFruits) {
  fruits = nextFruits
}

setFruits(5)

I think this example should either match your get example, or be completely different so it's not confusing, since get/set on an object is thought of to be a matching pair. Currently, I don't see a "benefit" of using this set function over a simple fruits = randomNumber() or fruits = 5 especially with the current scoping. If you were to match the getter method (get keyword), the example would look like this.

const bowl = {
  fruits: 0, 
  get fruitCount() { this.fruits },
  set fruitCount(val) { 
    if (typeof val === 'number') {
      fruits = val
  } else {
     throw new Error('You need to provide a number');
  }
}
console.log(bowl.fruitCount) // 0;
bowl.fruitCount = 5;
console.log(bowl.fruitCount) // 5;
bowl.fruitCount = "invalid"; // throws Error 

the key words, in js and other languages usually allow for those sorts of protections against setting (and getting a private field without exposing the field's value directly).

To avoid this confusion, I think you should either explain getters/setters vs a function with get/set in the name and provide an example of both, or more simply, use a pure function as an example.

function getRandomFruit() { /* returns a fruit */ }
function setTheme(palette) { /* changes UI theme to light | dark mode */ }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions