If I have an object and function
var obj {
\"1234\": {\"example\": \"sample\"},
\"5678\": {\"example\": \"sample\"}
}
function example(num, str) {
Why do I have to write obj[num] instead of obj.num?
Because obj[num]
takes the value of num
(for instance, 1234
) and uses that value as the property name, but obj.num
uses "num"
(literally) as the property name. Brackets vs. dot is how the JavaScript parser knows when you're giving the property name literally (dot notation) or using an expression you want to use the result of (brackets notation).
(Side note: Granted, when we do foo[1]
, we literally mean the property 1
in foo
. But from the parser's perspective, we're effectively using an expression there.)