Complex/variable object keys in JavaScript

While it’s pretty easy to use regular keys within objects in JavaScript, you may need to use complex keys (e.g. variable keys) from time to time. Using square bracket notation, that’s just as easy as regular keys.

var demo = {};

demo.a = 'Easy peasy';

demo['b'] = 'Same thing in square bracket notation';

var test = 'a b c';

demo[test] = 'Variable key';

The code above results the following object.

{
    "a": "Easy peasy",
    "b": "Same thing in square bracket notation",
    "a b c": "Variable key"
}