Posted over 1 year ago. Visible to the public.

JavaScript: Hash/Object with default value

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.

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

Copy
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.

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

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

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

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

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
over 1 year ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more