Declare a javascript object between brackets to choose only the element corresponding to its index

100 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

First some fixes

  • add 'function' before it is a function.

Here's a working sample:

    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(0));
    console.log(statusformId(1));
    console.log(statusformId(2));
    console.log(statusformId(3));
    console.log(statusformId(4));

which will returns

in the bed
face to your computer
a little bit silly
nowhere
Unknow status: 4

The why:

This represents an object with some indexes where 0 has the value, 'in the bed', ... .

{
  0: 'in the bed',
  1: 'face to your computer',
  2: 'a little bit silly',
  3: 'nowhere'
}

wrapping the object in a subexpression and adding the index will create the object and return the value of the passed index.

      const status = (
        {
          0: 'in the bed',
          1: 'face to your computer',
          2: 'a little bit silly',
          3: 'nowhere'
        }
      )[id];

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.

  return status || 'Unknow status: '+id
0
On
const a = {0:'zero'}
console.log(a[0]);

is same as

const a = ({0:'zero'})[0]
console.log(a);

You are ultimately trying to access the object property through index. Your code can be written as follows.

function statusformId(id){
      const status = {
          0: 'in the bed',
          1: 'face to your computer',
          2: 'a little bit silly',
          3: 'nowhere'
        }

      return status[id] || 'Unknow status: '+id
}

PS - Your code snippet is wrong. You have mistakenly added an extra '}' in your code block