0

I am using the following code in javascript:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

if(grouped.hasOwnProperty([keyToGroupBy])) {
   ...
}

Could someone provide a reference as to why using the brackets with keyToGroupBy is working preferably in mdn? Is this considered a hack(works by chance) or it is something commonly used? is there a better way to do the same?

Kyriakos
  • 49
  • 4
  • where do you see this example? – Nina Scholz Feb 04 '20 at 16:26
  • Converting a one element array to a string gives the one element converted to string. I didn't check, but i assume `hasOwnProperty` just uses `toString`. Example: `"" + [{ toString: () => "hi" }] === "hi"` – ASDFGerte Feb 04 '20 at 16:30
  • PS: just as a fun additional fact (not really relevant), you can modify this behavior, by making the property access "join" find a function other than the default `Array.prototype.join` first. I checked, `Object.prototype.hasOwnProperty` does a `ToPrimitive` and a `ToString` in sequence, so to make both fail, lets use an object that refuses to be a string: `let x = ["hi"]; var o = { toString: () => o }; x.join = () => o; ({}).hasOwnProperty(x);` and e.g. on FF, i get the error "TypeError: can't convert x to string". Welcome to javascribbidies! – ASDFGerte Feb 04 '20 at 16:48

1 Answers1

1

The "bracket notation" is not bracket notation. What you've defined there is an array literal for an array with one element:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

console.log(Array.isArray([keyToGroupBy]))

So, it "works" because the properties of objects are either strings or symbols. Since you're not supplying a Symbol, it's going to be turned into a string. And when you do that with an array, the result is...a string equal to the first element:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

let arr = [keyToGroupBy];

console.log(String(arr) === arr[0]);
console.log(String(arr));

Turning an array to a string involves internally calling Array#join() and since there are no other values, no separator would be produced and nothing will be added to the single string that is in the array.

So, you're doing a rather roundabout way of...just checking for the string.

Is this considered a hack(works by chance)

It's mostly a hack. It's not quite abusing the rules of type conversion but certainly skirting them.

or it is something commonly used?

No, it's not. There is no reason to wrap strings into arrays...and then convert them to a string again if all you need is a string in the first place.

is there a better way to do the same?

Yes, simply don't have an array literal anywhere: grouped.hasOwnProperty(keyToGroupBy)

VLAZ
  • 18,437
  • 8
  • 35
  • 54