Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSander Nicolaysen
5,474 PointsWhy is it possible to write if (prevLi)?
I don't understand how the prevLi evaluates to true in this code. prevLi is not a true of false value. It's an li element containing a bunch of properties, so how does the if statement know if this is true or not?
if (prevLi) { ul.insertBefore(li, prevLi); }
It would make more sense if we wrote: if (prevLi !== null) { ul.insertBefore(li, prevLi); }
3 Answers
Matthew Dodd
Full Stack JavaScript Techdegree Graduate 16,657 PointsHi Sander,
There are certain values in JS that are default true/false. Numbers, strings for example are always true. An empty string, undefined and null for example, are always false.
So the if statement checks if prevLi actually contains something, if prevLi does contain an li element, then its true. If it's empty or undefined, its false.
Here's a short article showing some of the truthy/falsy values in JS : https://www.sitepoint.com/javascript-truthy-falsy/
Camilo Lucero
27,692 PointsIt is not equal to true, but it is a truthy value. When no comparison operator is used, the value "truthiness" is evaluated. Truthy values are considered true and falsy values are considered false.
Truthy and falsy may sound a bit strange at first, but they are important concepts in conditional statements. Falsy values are:
- False
- Null
- Undefined
- 0
- NaN
- '' (empty string)
Everything that is not falsey will be evaluated to true. That is why prevLi in your case is evaluated to true, because it contains an element.
Sander Nicolaysen
5,474 PointsThank you !
Junior Aidee
Front End Web Development Techdegree Graduate 14,657 PointsJunior Aidee
Front End Web Development Techdegree Graduate 14,657 PointsJust making sure I understand this concept, in this example, the condition (prevLi) is evaluated to false since the first list element doesn't have any previous sibling. Correct?