Read more

JavaScript: Hash/Object with default value

Arne Hartherz
February 10, 2017Software engineer at makandra GmbH

You can easily have a JavaScript hash/object that returns a default value for unset keys/properties -- as long as you need to support only recent browsers.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

The key are JavaScript proxies Show archive.org snapshot from ECMAScript 6 that allow implementing a custom getter method. They work like this:

var hash = new Proxy({}, {
  get: function(object, property) {
    return object.hasOwnProperty(property) ? object[property] : 'hello';
  }
});

When you set a key, you can read its value just like always.

hash['foo'] = 23
hash['foo']
// => 23

But instead of returning undefined for unset keys, our get proxy now returns our default value.

hash['bar']
// => 'hello'

This is supported in Chrome 49+, Firefox 18+, Safari 10+, and Edge 13+.

Posted by Arne Hartherz to makandra dev (2017-02-10 11:25)