Angular.js: A problem with boolean expression evaluation in 1.4

Created on 28 May 2015  路  7Comments  路  Source: angular/angular.js

Greetings,

After upgrading to angular 1.4 we're having a problem with expressions like:

true && aMissingObject.aMissingProperty

They evaluate to true, instead of false (incidentally, true && !!aMissingObject.aMissingProperty evaluates to false).

Here is an example on plunkr:

http://plnkr.co/edit/4wVwHOO3lsc10JaSrIXI

Could you please comment if this is expected behaviour?

Many thanks

$parse regression bug

All 7 comments

Thanks for the report. This happens since 1.4.0-beta.3, so it looks like it's caused by the parse refactor. @lgalfaso can you take a look?

@SamuraiPrinciple thanks for reporting this! The fix landed and should be part of the next release

Indeed - just tried it on master and it works like a charm.

Much appreciated

@lgalfaso any idea on when this might land?

This already landed and should be part of 1.4.1 once released

Commenting on here as I can't seem to find anything related, I just ran into an issue similar to this. I had a line of code this.canEdit = this.item && this.item.id where I would normally expect the value to short-circuit to false when this.item is undefined, however it evaluated this.canEdit to undefined!

I had to rewrite the line to this.canEdit = this.item !== undefined && this.item.id !== undefined for it to evaluate to a boolean value. Weird?

This is on Angular @ 7.1

@jziggas This is actually the github for angularJS 1.x, but what you're doing is essentially evaluating

this.canEdit = undefined && 'Not Undefined'

Which does return undefined, so it seems to be working as expected.

image

You can use !! and parens to convert that statement into a bool like this

image

So essentially

this.canEdit = !!(this.item && this.item.id)

When either of these is falsey, it will return false

If you're wondering why does this happen, this is because logical and "&&" evaluates whether left of operator (this.item) can be evaluated to truthy. If so, it returns right of operator, otherwise returns left of operator. In your case this is undefined.

You can see the same if you did something like the following

image

two is returned because one is truthy.

And I realize this is getting quite long, but for the sake of completeness and a full answer I will explain the !!

With Parens you can evaluate the result of (this.item && this.item.id) which will be undefined.

So now you have

!!undefined

The ! operator returns false if its operand "undefined" is truthy otherwise true.

undefined is not truthy so now you have

!true

and the final result is obviously

false

Was this page helpful?
0 / 5 - 0 ratings