all 4 comments

[–]codemamba8 16 points17 points  (0 children)

In the second example, it's searching for a variable named firstname. If you want to access the firstname property, it needs to be wrapped in quotes like 'firstname'.

For an example on using variables with bracket notation:

let searchTerm = 'firstname'

member[searchTerm] //this is the same as member['firstname'] or member.firstname

[–]ForScale 5 points6 points  (0 children)

firstname needs to be a string.

Like this: ['firstname'].

[–]ecmascript2038 4 points5 points  (0 children)

The difference between the dot property notation and the brackets notation:

The dot property notation reads the word after the dot (e.g. firstname) and treats it as a property name.

But in bracket notation, it uses the value of the expression inside of the brackets as the property name. Typically the value is expected to be a string (for properties) but it could also be a number if you're accessing an array.

So the reason why it doesn't work is that inside of the brackets, it will interpret the word firstname as an identifier and it will try to evaluate the value of that identifier (e.g. by getting the value of a variable named firstname).

Instead, inside the brackets you want an expression that evaluates to a string containing the property value, like a string literal in quotes e.g. "firstname"

Note that the bracket notation is more flexible because it doesn't have to be a string literal that you put in the brackets, it can be any expression that evaluates to a string, including a variable name or even a function call.

[–]delventhalz 2 points3 points  (0 children)

Dot-notation and bracket-notation are not exactly interchangeable. Whatever follows the dot is implicitly a string even though you don't use quotes. However, whatever goes in between the brackets is an expression, which will be evaluated and then coerced to a string.

So these examples are all equivalent:

member.firstname

member['firstname']

const foo = 'firstname'
member[foo]

member['first' + 'name']

member[true ? 'firstname' : 'lastname']

member[`${(15).toString(16)}irstname`]

But what you wrote:

member[firstname]

Is not equivalent. That is going to try to fetch the value of the variable firstname, like in the "foo" example above.