2

Let's say we have this function:

loadView : function(view) {
    this.view && this.view.remove();
    this.view = view;
}

What does the first line do? For example if the line was this.view && this.otherView, it would return true if both view and otherView exists and false if one of them doesn't, but now there is a function being called at the end, which is confusing me.

Is the first line equivalent to:

if(this.view) {this.view.remove()}

?

  • 2
    Yes, the first line is equivalent to the `if` statement you posted - it's just a shorter version. It uses short-circuiting, as you've already pointed out (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-Circuit_Evaluation) - it only checks (executes) the second operand (the method call) if the first is truthy – Ian Jun 11 '14 at 15:50
  • 2
    Note: "*it would return true*" JavaScript's logical operators, `&&` and `||`, don't strictly return booleans. They return one of the 2 operands given to them after just testing the *truthiness* of the 1st. – Jonathan Lonowski Jun 11 '14 at 15:52

2 Answers2

3

it's a short circuit evaluation.

If this.view is "falsey" then this.view.remove() will not be evaluated.

So the answer to your question is yes.

mucio
  • 6,700
  • 1
  • 17
  • 30
1

It's called a guard operator. You would usually use && in this way

if(thing1 === 1 && thing2 === 2){}

You'll notice we want to check if BOTH things return true. Well the way it works is that we know that 'thing 2 === 0' will never run if the first expression (thing1 === 1) doesn't evaluate to true. Why run the second expression if they both have to be true and the first one already failed. Taking that knowledge we can now use it as a guard to not run the second expression, unless the first expression it true, or in this case truthy.

So in your code, this.view.remove() only runs if this.view is truthy.

Tyler McGinnis
  • 30,798
  • 16
  • 69
  • 74