I found this sample in a book and this is the first time that I see this notation.
Obviously it's a thousand times shorter than making a switch; but what is it?
When I do typeof(status)
it returns undefined.
I would like to understand what it is so that I can apply it more often in my next codes!
function statusformId(id) {
const status = ({
0: 'in the bed',
1: 'face to your computer',
2: 'a little bit silly',
3: 'nowhere'
})[id];
return status || 'Unknow status: ' + id;
}
console.log('statusformId(2) ...', statusformId(2)); // a little bit silly
console.log('statusformId() ...', statusformId()); // Unknow status: undefined
Thank you!
First some fixes
Here's a working sample:
which will returns
The why:
This represents an object with some indexes where 0 has the value, 'in the bed', ... .
wrapping the object in a subexpression and adding the index will create the object and return the value of the passed index.
When a id is used not known to the object, undefined is return. using
||
will return'Unknow status: '+id
when status has a falsy value (like undefined, null, false, ... ) , otherwise the actual value is returned.