Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created June 13, 2020 20:36
Show Gist options
  • Save prof3ssorSt3v3/a0e6780fc058a563feeb283c7b059c79 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/a0e6780fc058a563feeb283c7b059c79 to your computer and use it in GitHub Desktop.
/***
* Dynamic Object properties using square brackets
*/
let beverage = 'Beer';
const myObj = {
a: 1,
b: 2,
c: 3,
food: 'cheese',
propName: 'cheese',
beverage: 'Heineken', // beverage: 'Heineken'
[beverage]: 'corona', // Beer: 'corona'
};
let addProp = (obj, propName, propValue) => {
// obj.food = 'cheese';
obj[propName] = propValue;
obj.propName = propValue;
};
addProp(myObj, 'food', 'cheese');
@Ionut-B
Copy link

Ionut-B commented Jun 18, 2020

Amazing square brakets: it's working even in:

myFunction(id) {
let element = document.getElementById([id]);
}

@prof3ssorSt3v3
Copy link
Author

Amazing square brackets: it's working even in:

myFunction(id) {
let element = document.getElementById([id]);
}

They are cool. Your example would also work without the square brackets. The variable would be evaluated inside the ( ) because there are no quotation marks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment