0

today at work a friend show me a strange way to access an object attribute using a variable.

To make it simple to understand, first we define an object, then a variable with a key of this object as string, then we try to access this key on the object.

object = {"123": 1, "12":2}
key = "12"
console.log(object[key])

this would return 2 and is the right way to do.

So my friend was doing this on react

object = {"123": 1, "12":2}
key = "12"
console.log(object.[key])

Trying this code on webbrowser console, returns error, but on React it works.

Can someone tell me why???? I'm really curious to know why this no sense code works

ready snippet to try on pure js

https://jsfiddle.net/ozgvfw02/1/

3
  • 1
    console.log(object[key]) Commented Oct 28, 2021 at 14:24
  • stackoverflow.com/a/69487330/15781079 - you either use dot notation (.) or bracket notation ([]). You can't use both for accessing a single property Commented Oct 28, 2021 at 14:31
  • Just tried this in a react project... Errors out with immediate syntax error. You sure there wasn't an array, with a ? after the array variable name? Optional chaining could be used for this... Something like arr?.[index] Commented Oct 28, 2021 at 14:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.