-
Notifications
You must be signed in to change notification settings - Fork 26.8k
Closed
Labels
Description
This is my rule for accessing properties:
If the object has properties that is not accessible with dot notation, use subscript notation. Use dot notation otherwise.
So:
const objOne = {
'facebook': 'no idea',
'google-plus': 'no idea',
};
objOne['facebook'] = 'thanks';
objOne['google-plus'] = 'no thanks';
const objTwo = {
'facebook': 'no idea',
'googlePlus': 'no idea',
};
objTwo.facebook = 'thanks';
objTwo.googlePlus = 'no thanks';
With Airbnb style, you have to write like this:
obj.foo = true;
obj.bar = true;
obj['foo-bar'] = true;
obj.baz = true;
obj['foo-baz'] = true;
This looks very ugly to be honest.
My suggestion is this (which is also different from my own rule):
Prefer dot notation when accessing properties. Only use subscript notation when you have to. If you used subscript notation when accessing a property, use subscript for other all cases.
So:
function foo(providers) {
const myProvider = 'google-plus';
if (providers.facebook) { // This is okay
// ...
} else if (providers[myProvider]) { // This is okay
// ...
}
}
function bar(providers) {
if (providers['google-plus']) { // This is okay
// ...
} else if (providers['facebook']) { // This is okay
// ...
}
}
function baz(providers) {
if (providers['google-plus']) { // This is okay
// ...
} else if (providers.facebook) { // This is not okay
// ...
}
}
function boo(providers) {
if (providers['facebook']) { // This is not okay
// ...
}
}