Telerik blogs
JavascriptD_870

In this article we will explore a basic but yet super important concept in JavaScript. The "falsey" value of your data.

Many times in articles and documentation, you may find yourself running into terms like “falsey” value, or “truthy” value, which are not 100% clear - especially in JavaScript. Let’s nose dive into this fundamental concept together. 🤔

The Core

The first thing to keep in mind and to learn is that “falsey” is not the same as FALSE. When a variable is set to false, that is a boolean type value.

let myBoolean = false;
let anotherBoolean = true;

A boolean value is either true or false. But what then does it mean when something is “falsey”?

The Anything and the Everything

Take this next concept at face value. ANYTHING and EVERYTHING that has a value can be evaluated as truthy or falsy. Usually, to check the “falsey-ness” of something in code, you do this:

let value = null;
if (!value) // do something

Here’s your a-ha moment. Value is definitely not a boolean, and is actually being set strictly to null. What then is happening in line two? How is JavaScript evaluating this null value in an if statement that clearly has to check for a true/false condition?

The answer is, as you guessed, the “falseyness” of the value.

Diving in

Technically speaking, there are only six values that would “trigger” a falsey check in an if statement like we had before. Let’s take a look.


1. undefined

You get this when a variable doesn’t have a value.

let noValue; // We don't assign a value here, so it defaults to undefined

if (noValue) {
  // This won't be reached
} 

if (!noValue) {
  // This will be reached
}

2. null

Whenever a variable is declared as null, this will be falsey.

let nullValue = null;
let object = { prop: null }

if (!nullValue) {
  // This will execute
}

if (!object.prop) {
  // This will execute too
}

3. NaN

You get NaN from performing invalid math operations, and it too will evaluate to falsey.

let result = Math.sqrt(-1)
let invalid = parseInt('thisisnotanumberwhatareyoudoingwithyourlife')

if (!result && !invalid) {
  // This would execute since both are falsey and NaN!
}

4 and 5. 0 and "" (empty strings)

Another way to usually represent false Boolean values is, of course, the number 0, and its counterpart true is represented by the number 1.

This means that anything that is trying to be evaluated as falsey that has a number 0 will be interpreted as FALSE. Be careful with this common gotcha.

Empty strings are ALSO evaluated as false, as you will see in the example.

let emptyString = "";
let numericZero = 2 - 2;

if (!emptyString) { 
  // Empty strings are falsey
}

if (!numericZero) {
  // This would also execute, since 2 - 2 = 0 (MIND. BLOWN.)
}

The final and 6th value is… drumrolls

6. Boolean false! :)
I will not insult your intelligence with an example, don’t worry.

Dem Arrays, tho

So, maybe you’re thinking about arrays now. And maybe you’re thinking, ok, so I would think if an array is empty, or its length === 0, then it should be falsey. Right?

WRONG!

const myCoolArray = [];
if (!myCoolArray) {
  // Get all the moneyz
} else {
  // Lose all the moneyz
}

Bad news. You lost the moneyz. This is a VERY common gotcha in JavaScript programming. Always remember that any array or object, even if empty, will evaluate to true when inspected inside a conditional.

Let’s get freaky with arrays though. What happens if we actually evaluate an array with an “equal to” == to a boolean false? (Note, we’re doing “equal to”, not “equal to and equal type” which would be === also called “identical.”)

const emptyArray = []

if (!emptyArray) {
  // Ok, so this would not get reached, because it's "truthy"
}

if (emptyArray == false) {
  // This actually WOULD execute. Whoa, ok? What?
}

if (emptyArray == true) {
  // This does not get executed!
}

if (emptyArray === false) {
  // This would NOT run, because emptyArray is of type ARRAY and false is a BOOLEAN
}

Beware of the Binaries

Ok well, maybe not the binaries, but do keep an eye out for number types when making your evaluations.

Consider the following example.

const gameData = {
  playerIndex: 0,
  totalPlayers: 1
}

if (gameData.playerIndex) {
  awardPointsToPlayer(gameData.playerIndex)
}

if (!gameData.totalPlayers) {
  weHaveNoPlayers()  
  createSomePlayers()
}

In this example, we have two major problems. The first one is that gameData.totalGames is a number type with value 0. In our conditional, we are trying to check if we have a player index, and then award her some points, but this code will in fact never be executed. JavaScript will evaluate the type of the 0 to numeric and will assert a falsey value.

In the second example, we are trying to check if we are lacking players. However, we are also not going to get our code executed, because the numeric type 1 will assert to a truthy value, and our ! looking for the falsey value will assert false - and will not execute.

How Do I Avoid These Problems?

Well, the first and best way to avoid falling into these caveats is knowing what’s causing them, and now you do! But I would encourage two tips.

  1. Avoid == like the plague. JavaScript is very squirmish with type evaluations. Get into the habit of using === and checking for type as well and you will avoid many headaches.

  2. If you are evaluating numeric values, be explicit about your comparisons. For example, in the above example, we could refactor our checks to the following.

const gameData = {
  playerIndex: 0,
  totalPlayers: 1
}

if (gameData.playerIndex >= 0) {
  awardPointsToPlayer(gameData.playerIndex)
}

if (gameData.totalPlayers === 0) {
  weHaveNoPlayers()  
  createSomePlayers()
}

Just make sure you’re not passing strings instead of numbers, because those will fail with type comparisons :)

 

For More Info on Building Great Web Apps

Want to learn more about creating great web apps? It all starts out with Kendo UI - the complete UI component library that allows you to quickly build high-quality, responsive apps. It includes everything you need, from grids and charts to dropdowns and gauges.

Learn More about Kendo UI

Get a Free Trial of Kendo UI


About the Author

Marina Mosti

Marina Mosti is a frontend web developer with over 18 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue, as well as writing articles and tutorials for the community. In her spare time, she enjoys playing bass, drums and video games.

Comments

Comments are disabled in preview mode.