2

Why does first work and not the latter?? *its only a minor difference where in the latter case i used the shorthand for accessing cats object property. I read that it shouldn't make any difference if "name of the property would be a valid variable name ― when it doesn't have any spaces or symbols in it and does not start with a digit character."

    //this works 
    var cats = {Spot:true};

    function addCat (name) {   cats[name] = true; }

    addCat("white");

    console.log ("white" in cats);  //true

    console.log (cats.white); //true

    //this doesn't work 
    var cats = {Spot:true};

    function addCat (name) {   cats.name = true; }

    addCat("white");

    console.log ("white" in cats); //false

    console.log (cats.white); //undefined
4
  • cats.name is not dynamic. Commented Jul 18, 2013 at 19:01
  • Try console.log(cats) and you'll see your problem Commented Jul 18, 2013 at 19:03
  • cats.name sets a property called 'name' on cats. Commented Jul 18, 2013 at 19:05
  • Also duplicate of Difference between using bracket ([]) and dot (.) notation Commented Jul 18, 2013 at 19:08

1 Answer 1

5

In your second code, cats.name is not dynamic so your not getting the value of name in the function; however, you are setting a property called name:

//this works
var cats = {
    Spot: true
};

function addCat (name) {   
    cats.name = true; 
    // use cats[name] like in your first example
}
addCat("white");

console.log(cats); 
/*
{
    Spot: true,
    name: true
}
*/

console.log ("name" in cats); //true
console.log (cats.name); // true
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.