1

hello guys i'm beginner of javascript! I know there are two ways to get object value

if there is object

object = {
   1:"one",
   2:"two".
}

1st : object.1 2nd : object[1]

but i wonder why this code has error

var product = {
    1:{title:'The history of web'},
    2:{title:'The next web'}
};

for(var name in product){
    product[name].title -> OK
    product.name.title -> error!!
}

what is difference between two codes!

PrepareFor
  • 2,448
  • 6
  • 22
  • 36
  • 1
    `product[name]` is used to access property dynamically. Here `name` will be replaced by it's value and that property is searched in `product`. `product.name` will search for `name` property in `product` which doesn't exists, so result will be `undefined` and you cannot access `title` of `undefined`. – Tushar Feb 08 '17 at 04:08
  • thanks a lot to your knowledge and kindness...!! thanks!!! – PrepareFor Feb 08 '17 at 04:18
  • and may i ask one more question? var user{ username:'aaa', password:'1111' } user.username -> OK but user[username] is error what is the problem? – PrepareFor Feb 08 '17 at 04:22
  • As explained in previous comment, when using bracket notation, the value of variable is replaced by it's value, i.e. `undefined` in this case, thus error. You need to wrap it in quotes `user['username']`. – Tushar Feb 08 '17 at 04:25
  • it should be user["username"] single quatation is not accepted – anis programmer Feb 08 '17 at 05:06

0 Answers0