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
user2426598
  • 314
  • 1
  • 10

1 Answers1

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
Shawn31313
  • 5,978
  • 4
  • 38
  • 80