Reputation: 291
In the condition
portion of the following ternary
statement, does playlist.length
equal playlist.length >= 1
?
var playlist = ["video1", "video2", "video3", "video4", "video5"];
// some code here
alert ((playlist.length) ?
playlist.length + "video(s) remain in the playlist: " + playlist.join (", ") + "."
: "No videos remain in the playlist");
Likewise, in the following snippet of code, does ! playlist.length
equal playlist.length === 0
?
alert ((! playlist.length) ?
"No videos in the playlist."
: playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + ".");
This is the first time I've seen an example where the
condition
portion of aternary
orif
statement does not include such a notation as===
or>=
. So I'm not sure how to interpret this.
Upvotes: 3
Views: 2348
Reputation: 19719
The two are very similar: !playlist.length
and playlist.length === 0
.
However, they are not exacty the same. In fact, here:
var playlist1 = [];
var playlist2 = {};
!playlist1.length // true
!playlist2.length // true
playlist1.length === 0 // true
playlist1.length === 0 // false
In that sense !playlist.length
also can be used on all kinds of objects, not just arrays.
In any case, when using this on an array, it is a way to check if the array is empty, and works as you have suggested, the same as playlist.length === 0
.
Upvotes: 1
Reputation: 350
In javascript 0 equals false, and any other number value equals true, but if you use === it compare value types too.
Upvotes: 0
Reputation: 82277
0 is implicitly converted to false in boolean comparisons in JavaScript. So when the length is 0, that is false. Conversely, any other number is implicitly converted to true in boolean comparisons in JavaScript. So when the length is anything but 0 it is true.
An easy test is to use !!
to see the "truthy" value
!!1 === true
!!0 === false
!!6 === true
Upvotes: 4
Reputation: 17630
The part to the left of the ?
is simply evaluated for "truthiness". The value 0
is "falsy" so evaluates as false for the purposes of the test. Numeric values other than 0
are "truish" and therefore for this purpose evaluate to true.
All other behaviors of the ternary are the same.
The ===
and !==
simply add the additional constraint that the L-value and R-value must also be the same type.
Upvotes: 1