Using-objects-for-lookups

result = lookup[val]
here what is logic behind these brackets and val?
can someone explain it?

An object looks like {key: 'value'}, to access the object you need to use the key which will give you the value

console.log({key: 'value'}.key) //'value'
//or
const obj = {key: 'value'};
console.log(obj.key) //'value'

In the above example I used dot notation to access the object, but sometimes you need to use bracket notation (bracket notation can do anything dot notation can, but dot notation cannot do everything bracket notation can).
In the case that your key has a character in it that would make it an invalid variable or you are accessing the object dynamically you will need to use bracket notation.

//the key of this object has a space in its name so I will
//need to use bracket notation to get its value
const obj = {'space in key': 'value'};
console.log(obj['space in key']) //'value'

//The variable key now points towards a string that is a valid
//key for the obj object so I can use the variable to access 
//the object, but I'll have to use bracket notation for it 
//to work 
let key = 'space in key'
console.log(obj[key]) //'value'
1 Like

result = lookup[val]
why there is ‘val’ instead of one of ‘keys’ inside the lookup object?like bravo , delta?

Val is a variable that holds a string with the name of one of the keys.

1 Like
obj = {kk: 'somevalue'}
varbl = 'kk'
obj.kk         //this will work, there is a key named 'kk'
obj.varbl        //this will not work, no key named 'varbl'
obj['kk']      //this will work, there is a key named 'kk'
obj[varbl]      //this will work, there is a key named 'kk'

edit

Changed var to varbl as ieahleen suggested.

1 Like

maybe a different example? you can’t have a variable named var

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.