Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question

marked as duplicate by Felix Kling, Fabrício Matté, Bergi, bfavaretto, Paul Mougel Mar 2 at 10:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
cats.name is not dynamic. –  Shawn31313 Jul 18 '13 at 19:01
    
Try console.log(cats) and you'll see your problem –  Bergi Jul 18 '13 at 19:03
    
cats.name sets a property called 'name' on cats. –  Rocket Hazmat Jul 18 '13 at 19:05
    
Also duplicate of Difference between using bracket ([]) and dot (.) notation –  Felix Kling Jul 18 '13 at 19:08

1 Answer 1

up vote 5 down vote accepted

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
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.