Is this a bug in JavaScript object literals, at least the parser?
////////// a bug in JavaScript? //////////
// works:
const pointless = {
"a b": 1,
"c": 2
};
// works:
({
"a b": 1,
"c": 2
});
// fails when uncommented:
// {
// "a b": 1,
// "c": 2
// };
////////// what lead to the above //////////
// works:
class Thing {
static get table() {
return {
'x': function () { console.log('You chose x!') },
'y': function () { console.log('You chose y!') }
};
}
static doAllTheThings(arg) {
this.table[arg]();
}
}
Thing.doAllTheThings('x');
// works:
function doAllTheThings(arg) {
({
'x': function () { console.log('You chose x!') },
'y': function () { console.log('You chose y!') }
})[arg]();
}
doAllTheThings('y');
// fails when uncommented:
// function doAllTheThings(arg) {
// {
// 'x': function () { console.log('You chose x!') },
// 'y': function () { console.log('You chose y!') }
// }[arg]();
// }
// doAllTheThings('y');
Live demo at: https://repl.it/repls/DeadlyFatherlyVertex
I stumbled onto this trying to make a jump table instead of using a giant switch command. Wrapping the {}
in ()
works but IMHO shouldn't be necessary.
Is there a reason it works this way?