Skip to content Skip to sidebar Skip to footer

Mdn Reference For Using Hasownproperty With Bracket Notation

I am using the following code in javascript: let group = false; let internalId = 'someString'; let appliedTo = 'someOtherString'; let keyToGroupBy = true === group ? internalId : a

Solution 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)

Post a Comment for "Mdn Reference For Using Hasownproperty With Bracket Notation"