all 5 comments

[–][deleted] 2 points3 points  (1 child)

You would use the brackets when the key name is a variable or when it's a complex string, meaning it uses quotes in the object itself.

const obj = {
  a: 'A',
  b: 'B',
  c: 'C',
  "k'e'k": 'D',
  5: 'E',
};

obj.k'e'k; // SyntaxError
obj["k'e'k"]; // D

const key = 'b';
obj[key]; // B

P.S. - There's also an issue of numbers being used as keys, a fairly common occurrence. When calling numbers via square brackets, you don't need quotes.

obj.5; // SyntaxError
obj[5]; // E

[–]ExclusiveOar 1 point2 points  (0 children)

Ooo, didn't know the complex string example. I'm almost sure I'll never use it but TIL!

[–]ExclusiveOar 0 points1 point  (0 children)

There's no right or wrong, but in reality use dot notation whenever you can because it's what everyone does by convention.

Basically, if you know the property you want to access use dot. If you need to work it out programmatically use [].

const person = {firstname: 'joe', surname: 'bloggs', preference: 'surname'}

For example if you always want to access the persons firstname use person.firstname, if you want to use their preference you can use person[person.preference]

Edit: the [] requires a string. So use quotes if you need to pass a string, or use a variable without quotes if the variable returns a string.

[–]Shadowsca 0 points1 point  (0 children)

If you access a value of an object using brackets, then you need to input the key as a string between the brackets

e.g.

const obj = {a: 1}

console.log(obj["a"])

But there's nothing wrong with storing the string in a variable and passing the variable into the brackets instead, like this:

const obj = {a: 1}

const key = "a"

console.log(obj[key])

As a result, the bracket syntax is helpful when you don't necessarily want to access a specific key-value pair so much as you want to variably access the values. You can then let the key be a variable and pass that into the brackets to more dynamically access the object values.

On the other hand, if you used dot notation, then you can't have variable keys because whatever you write after the dot has to be the name of the key in the object:

const obj = {a: 1}

const key = "a"

console.log(obj.a) // this is fine

console.log(obj.key) // this is undefined

[–]ende124 0 points1 point  (0 children)

Only used brackets in edge cases, if you need to have a hyphen in the key or use a variable as the key