0

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;

}

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is kind of a sparse answer but I can’t find a good duplicate. Posted because it’s important to have something less misleading.
Thank you so much, your answer is perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.