Q:

Adding new value to javascript associative array "on the fly" when trying to get value by not existing key

Is it possible to create and return new element of associative array "on the fly" when trying to get value by not existing key?
a = {};
a[5]; // return "fezzes"; a = {5: "fezzs"}
a[9]; // return "jtte";  a = {5: "fezzs", 9: "jtte"}

A:

The best way to handle undefined object properties would be to use a Proxy object (and this answer has covers a similar use case):
a = { 1 : "hello" };

console.log(a[1]); //hello
console.log(a[2]); //undefined

var handler = {
    get: function(target, name){
        if (!(name in target)) {
            target[name] = "world";
        }
        return target[name];
    }
};

var p = new Proxy(a, handler);

console.log(a[1]); //hello
console.log(a[2]); //world

Proxies are a (nice) ES6 features. Firefox supports them since version 18, while in Chrome (and in Node.js) you have to enable the harmony flag.

