0
  1. const first= {a: 2, b: 3}

  2. const second= {"a": 2, "b": 3}

Even though both examples given above print the same in console, I can't access the values of those objects the same way. To access the key of first object, I have to write console.log( first.a ) and for second object console.log( first[a] ).

So if they are printing the same, why should I have to access them in different way. If the keys in first object aren't characters then what are they...

Below code is the reason why I got this question

const maxchar = (str)=>{
  let charCount = {}
  for (let index = 0; index < str.length; index++) {
    const char = str[index]
    charCount[char] = charCount[char]+ 1|| 1 //can't access char as charCount.char
  }
  return charCount
}
Triet Doan
  • 11,455
  • 8
  • 36
  • 69
Bhargav v
  • 35
  • 3
  • 1. and 2. are *identical* - there is literally no difference. The quotes are optional in this case. `first.a` and `first[a]` are completely different. The second one will [dynamically access object property using variable](https://stackoverflow.com/q/4244896) and in this case the variable is `a`. So, depends on what the variable contains. Your code also does dynamic accessing by a variable, there isn't a `.char` property on that object. The key would be whatever the *variable* called `char` contains. I'm not clear how that relates to the beginning of the question, though. – VLAZ Jan 27 '21 at 17:04
  • You are trying `console.log(first[a])`. Did you mean `console.log(first['a'])` (not the quotes around `a`)? – Thijs Jan 27 '21 at 17:05
  • 1
    **I think you just** ***nailed it,*** **Thijs!** (Show-of-hands how many people at first failed to notice that `a` is a *variable* reference? Yes, my hand is raised.) When you use "dot" notation, the language understands that the identifier following the dot refers to a member. But when you use "array" notation, the value within the brackets is an *expression,* whose value must match the name of a member. *(Most likely, JavaScript printed an error-message to the console log which the OP failed to notice, "and just kept right on going," as JS always does.)* – Mike Robinson Jan 27 '21 at 19:15

1 Answers1

0

Regarding your first question: there is no difference between your 1st and 2nd example.

For your second question, let's look at this small example:

charCount = { a: 2, b:3 }
char = 'a'
print(charCount[char]) // 2
print(charCount.char) // error

As pointed out in the comment, when you call charCount[char], it will dynamically access object property using variable. What it does is just simply replace the variable char with its current value (which is a in this case). So, the call becomes charCount['a'], and you got the result.

When you call charCount.char, it literally tries to access the property named char of the object charCount. In this case, that property does not exist, which is why you got an error.

Triet Doan
  • 11,455
  • 8
  • 36
  • 69