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 trial

JavaScript JavaScript and the DOM (Retiring) Traversing the DOM Using previousElementSibling and insertBefore

Sander Nicolaysen
Sander Nicolaysen
5,474 Points

Why 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Matthew Dodd
Full Stack JavaScript Techdegree Graduate 16,657 Points

Hi 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/

Just 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?

Camilo Lucero
Camilo Lucero
27,692 Points

It 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:

  1. False
  2. Null
  3. Undefined
  4. 0
  5. NaN
  6. '' (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.