0

If I have an object and function

var obj {
    "1234": {"example": "sample"},
    "5678": {"example": "sample"}
}    

function example(num, str) {
    if obj[num].hasOwnProperty(str) {
        //manipulate property
    }
    return obj;
}

then later call the function,

obj(1234, "example")

Why do I have to write obj[num] instead of obj.num? Shouldn't dot notation be acceptable because the value being passed will always be an integer and not have quotations around it, i.e. obj.1234 would work but not obj."string"?

1
  • Side note: If you want, you can drop the quotes on the property names in the object initializer. Numeric literals are valid there: var obj = { 1234: {"example": "sample"} ... Commented Dec 10, 2016 at 18:15

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

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.