1

trying to understand the exact different between using . and [] to get a value from an object:

const o = {name: "aaa", family: "bbb"};
print(o["name"]);
print(o.name);

Are there any cases that one would be preferable over the other one?

  • 1
    What if the name of the property wasn't a valid identifier? What if it was coming in dynamically as a string value? – jonrsharpe Jul 26 '18 at 15:38
  • @jonrsharpe can you explaine more please? – ILoveReactAndNode Jul 26 '18 at 15:38
  • 1
    What if you started with `{ 'hello world': 3 }`. How do you get `3`? What if you have `const a = 'hello world'`? – jonrsharpe Jul 26 '18 at 15:39
  • @jonrsharpe oh i see, so in case that it's dynamically coming from somewhere we use [], right? – ILoveReactAndNode Jul 26 '18 at 15:39
  • 1
    The benefit of the first example is that you can do `var propertyName = 'name'; print (o[propertyName]);` If you don't know until runtime which property you want to read, that's good. If you do know at runtime then the second way is simpler and safer. – Scott Hannen Jul 26 '18 at 15:40
  • Why the downvotes? I'm not clear how this "Doesn't show research effort, is unclear or not helpful"? – Liam Jul 26 '18 at 15:40
  • @Liam thanks for that – ILoveReactAndNode Jul 26 '18 at 15:41
  • 1
    In a nutshell: `.` must use a *valid identifier*, `[]` takes any *expression*. `.` is shorter, but more limited. – deceze Jul 26 '18 at 15:41
  • There are some key differences. For example, bracket notation can be used with variables while dot cannot. const selector = "name" const o = {name: "aaa", family: "bbb"}; console.log(o[selector]) --selects name console.log(o.selector) --fails – Saddy Jul 26 '18 at 15:41
  • Thank all, can one please post it as an answer? – ILoveReactAndNode Jul 26 '18 at 15:52

0 Answers0