I was working with ng-flow example for basic image upload. I saw an expression which I didn't understand how it works.
Basically, this is the expression:
<p>Demo object array expression in Javascript:</p>
<p id="demo"></p>
<script>
var expr = !!{png:1,gif:1,jpg:1,jpeg:1}['pdf', 'gif', 'jpg'];
document.getElementById("demo").innerHTML = expr ;
</script>
It seems that the above means return true if the array has a valid image in the last element. I am not sure why, but after I studied the code, this is my conclusion.
Appreciate if someone could help me understand the above and give me a link for documentation. I searched everywhere but didn't find any reference.
Click here to see the html which has this expression from ng-flow
I think the intention of the code is to disable upload of the file if it is not an image.
Anyone could recommend and easier alternative, please let me know.
Tarek
There's actually quite a bit going on in that statement but it's mostly just boolean logic.
First look at the statement
['pdf', 'gif', 'jpg']
. This contains the javascript,
operator which sets the return value of the statement it's contained in to the value after the last comma.E.g.
In this case this case it resolves to
['jpg']
Some documentation on that here:
Javascript comma operator
And as you probably already guessed, the
!
returns a boolean expression that reverses the value of atruthy
ortrue
statement tofalse
and afalsey
orfalse
statement totrue
.{png:1,gif:1,jpg:1,jpeg:1}['jpg'];
is1
which is atruthy
value.!1
becomesfalse
. Finally!false
is simplytrue
;See more here:
Truthy
Falsy
Logical operators