YPCrumble
YPCrumble

Reputation: 28722

What does !this mean in javascript?

As in this function, that toggles the 'completed' state of a todo item from true to false and back:

toggle: function() {
  this.save({
    completed: !this.get('completed') 
  });
}

Upvotes: 2

Views: 369

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92324

Assuming you know that ! means negation (converts to boolean and returns the opposite value), what you posted is the same as

!(this.get('completed')) 

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Notice that the . comes before the ! on that table. That's why the ! is associated with the whole expression, the . gets associated with get() before the ! comes into play.

Upvotes: 9

Adam Cameron
Adam Cameron

Reputation: 29870

The other answer is a technically fine general answer, and absolutely correct.

For your particular situation, you have a method in the current (this) object called get(), which returns a boolean value. So using the not operator (!) on the boolean return value from get() reverses it, so if get() returns true, the expression becomes false (etc). Meaning you are passing a value of the opposite of what's returned from get() as the value for the completed property of the object passed into the call to save().

Upvotes: 0

Related Questions