when I use test.tested-by, the javascript reports -by is undefined. I am sure test contains tested-by property. Any solution here?
            Asked
            
        
        
            Active
            
        
            Viewed 139 times
        
    2
            
            
        - 
                    See http://mathiasbynens.be/notes/javascript-properties and http://mothereff.in/js-properties#tested-by :) – Mathias Bynens Jul 29 '12 at 07:45
3 Answers
5
            Try using test['tested-by'] instead. tested-by looks like tested minus by
 
    
    
        Rob
        
- 1,865
- 1
- 14
- 26
- 
                    Best practice is often to avoid it. I like the `.` syntax better, but this is correct. – beatgammit May 24 '11 at 06:32
- 
                    See http://mathiasbynens.be/notes/javascript-properties and http://mothereff.in/js-properties#tested-by :) – Mathias Bynens Jul 29 '12 at 07:45
3
            
            
        You need to use:
test["tested-by"]
This way you can provide any property name, even reserved keywords (like "class").
 
    
    
        MBO
        
- 30,379
- 5
- 50
- 52
1
            
            
        See another question here: What characters are valid for JavaScript variable names?
Basically, a - is not a valid variable character in javascript.
The - character is also not a valid IdentifierName character, which means you cannot use the dot notation. test.tested-by does not access the property tested-by. (You can use test['tested-by'].)
- 
                    This has little to do with variable names, but rather with property names. The rules are similar but not exactly the same: http://mathiasbynens.be/notes/javascript-properties – Mathias Bynens Jul 29 '12 at 07:45
- 
                    From that site: `Dot notation can only be used when the property name is a valid identifier name.` And that's what you are trying to do in your question. – Arjan Jul 29 '12 at 07:57
- 
                    Not my question (I am not the OP). Anyway, variable names in JavaScript are `Identifier`s, not `IdentifierName`s (which is the grammar that applies to property names). You’re confusing the two. `Identifier`s are `IdentifierName`s that are not `ReservedWord`s. For example, `var default;` throws a `SyntaxError`, while `var object = { default: 42 };` is fine as per the spec. See http://mathiasbynens.be/notes/javascript-identifiers for more info. In other words, your answer is correct, but it’s not the answer to OP’s question. – Mathias Bynens Jul 29 '12 at 20:36
- 
                    Or it does answer the question but uses incorrect terminology which can get confusing. So I updated my answer. – Arjan Jul 29 '12 at 22:18
 
     
    