DEV Community

Discussion on: 3 Ways to Set Default Value in JavaScript

Collapse
 
tombarr profile image
Thomas Barrasso

Nice article, I would love to see the Elvis operator in Javascript!

Another way you can assign default values is with Proxy. This can be done explicitly, implicitly, on a per-type basis, etc.

const withZeroValue = (target, zeroValue = 0) => new Proxy(target, {
  get: (obj, prop) => (prop in obj) ? obj[prop] : zeroValue
})

let position = withZeroValue({
  x: 10,
  y: 15
})

position.z // 0