Elijah.S
Elijah.S

Reputation: 47

Calling an object property from within a variable vs outside a variable (JS)

Whats the difference between the two calls? It almost seems identical but running it tells me otherwise. Calling the property from within the variable, and outside the variable seem to be calling different things but I'm not sure how or why.

PS. Cheese is a boolean property set to false.

  toggleCheese: function(position) {
    var pizza = this.pizza[position].cheese;
    pizza = !pizza;

}

vs

  toggleCheese: function(position) {
    var pizza= this.pizza[position];
    pizza.cheese = !pizza.cheese;

}

Upvotes: 0

Views: 76

Answers (1)

Ry-
Ry-

Reputation: 224867

Let’s cut this down to the important parts. Say you have an object representing a very simple pizza,
{ cheese: false }. We’ll make a variable pizza and point it at the object:

var pizza = { cheese: false };

then make another variable cheese and point it at the value of the object’s cheese property:

var cheese = pizza.cheese;

Now, the difference between these two:

cheese = true;
pizza.cheese = true;

is that the former means “point the variable cheese to true” and the latter means “take the value the variable pizza points at, and point its cheese property to true”. One only affects the cheese variable, and the other affects the pizza object like you want. In other words, these are really two unrelated forms of the assignment operation:

<variable> = <value>;
<value>.<property> = <value>;

If you want to set a variable, use the variable form; if you want to set a property, use the property form.

Upvotes: 1

Related Questions