I have been using square bracket notation in Javascript to create and call associative arrays.
In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.
How would you do something like this in dot notation?
var item = {};
item['1'] = 'pen';
var x = 1;
console.log(item[x]); // console will show 'pen'
You can't use variables in dot notation (short of using eval
, which you don't want to do). With dot notation the property name is essentially a constant.
myObj.propName
// is equivalent to
myObj["propName"]
You actually can now.
In this case you can use square brackets to use a variable for dot notation.
console.log(item.[x])
This is especially useful for use in Typescript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With