JavaScript JavaScript and the DOM 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
Matthew Dodd
Full Stack JavaScript Techdegree Graduate 16,651 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 :

Camilo Lucero
Camilo Lucero
26,508 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.