1

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];
Marvin
  • 853
  • 2
  • 14
  • 38
themadking
  • 67
  • 1
  • 7
  • 3
    It's a property accessor for an object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation – Nick Parsons Feb 18 '19 at 01:41
  • OHH! It makes more sense now. So it's like accessing an array at that index. Thanks! – themadking Feb 18 '19 at 01:47
  • It's an object literal followed by property access. Same as `let chars = {'1':0x1, ...}; idx = chars[charStr];`. – RobG Feb 18 '19 at 01:49

3 Answers3

3

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

Marvin
  • 853
  • 2
  • 14
  • 38
2

basically what you are seeing is the accessing of a property in an object directly in the same definition.

lets use a simplier example:

const ourObjectResponse = {
    foo: 'bar'
}['foo']
console.log(ourObjectResponse) // 'bar'

this is because what you are doing is defining an object and inmediatly getting a value from that object.

you can change this to be something like:

const ourObject = {
    foo: 'bar'
};
const ourObjectResponse = ourObject['foo']
console.log(ourObjectResponse) // 'bar'
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0

You can access property of object using square box notations. This is helpful usually in cases where the property has space in it. Like obj[‘first name’].

Sagar Agrawal
  • 639
  • 1
  • 7
  • 17