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.
var a = 1, 2, 'foo'; // a -> 'foo'
var foo = ['a', 'b', 'c'];
foo[0, 2, 1]; // foo[0, 2, 1] -> foo[1] -> 'b'
In this case this case it resolves to ['jpg']
Some documentation on that here:
And as you probably already guessed, the !
returns a boolean expression that reverses the value of a truthy
or true
statement to false
and a falsey
or false
statement to true
.
{png:1,gif:1,jpg:1,jpeg:1}['jpg'];
is 1
which is a truthy
value. !1
becomes false
. Finally !false
is simply true
;
See more here: