Search code examples
javascriptobject-notation

What does this square bracket suffix at the end of the object definition in JavaScript mean?


JavaScript code

I was browsing someone's code on GitHub and came across this and have no idea what this means. I would have googled but I am new to JavaScript and have no idea how to google it. Any information would be appreciated!

var charStr = String.fromCharCode(evt.which);
var value   = (evt.type == 'keydown') ? true : false;

idx = {
  '1': 0x1,'2': 0x2,'3': 0x3,'4': 0x4,
  'Q': 0x4,'W':0x5,'E': 0x6,'R': 0xD,
  'A': 0x7,'S':0x8,'D': 0x9,'F': 0xE,
  'Z': 0xA,'X':0x0,'C': 0xB, 'V':0xF,
}[charStr];

Solution

  • This is the same as saying:

    const idxObj = {
      '1': 0x1,'2': 0x2,'3': 0x3,'4': 0x4,
      'Q': 0x4,'W':0x5,'E': 0x6,'R': 0xD,
      'A': 0x7,'S':0x8,'D': 0x9,'F': 0xE,
      'Z': 0xA,'X':0x0,'C': 0xB, 'V':0xF,
    };
    idx = idxObj[charStr];
    

    It is creating the object and accessing an object property at the same time.

    Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation