1

I wonder what difference between a[x] and a.x

When I create a={}

when I write a.x=5 it gives {x:5}

but when I write a[x]=5 it gives error

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors – epascarello Sep 03 '20 at 16:18
  • 2
    `a[x]` and `a.x` are very different, but `a['x']` and `a.x` are very similar. – Joachim Sauer Sep 03 '20 at 16:18
  • "a[x]=5 it gives error" because it is looking for a variable `x` which you did not define. If you defined a variable x, it would be the string `var x = 'x'; console.log(a[x]);` – epascarello Sep 03 '20 at 16:19
  • In case of `a[x]`, javascript will look for an identifier named `x` and if it exists then its value will be used as a property name. If it doesn't exists, you will get an error – Yousaf Sep 03 '20 at 16:20
  • `x = 'y'; return a[x];` would give you the same result as `return a.y` – TKoL Sep 03 '20 at 16:20

0 Answers0