Search code examples
javascriptasync-awaitgetter-setter

What is a Virtual Getter and Setter in Javascript?


What is the idea behind a virtual getter and setter? Why do we need them?

I'm writing the following code while watching a tutorial:

login: async args => {
  const user = await User.findOne(args.email)
  if (!user) {
    throw new Error("Email doesn't exist!")
  }
  const isEqual = await bcrypt.compare(args.password, user.password)
  if (!isEqual) {
    throw new Error("Wrong Password!")
  }
  jwt.sign({userId: user.id})
}

I'm making use of a virtual getter here to extract user.id but I don't really understand what's going on here.

I'm using Mongoose.


Solution

  • Nothing is "going on" here, you're getting the id property of the user.

    "Virtual attributes" (as commonly defined in JS, anyway) is a property that looks like an attribute, but may be computed (via setting, getting, or both).

    You "need" them if you want to perform additional logic upon setting or getting a property, for various values of "need": you never need them, but you may want them–and sometimes they're great.

    There are potential downsides to over-using getters/setters, like (at least AFAIK) you can't make getters or setters async, which may be problematic in some situations, e.g., Mongoose's set takes a function that'll be turned into a property setter, but you can't make it async: https://github.com/Automattic/mongoose/issues/2571