javascriptecmascript-6iterationvalue-iteration

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


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!


Solution

  • First some fixes

    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