Values and types · 10 min · free lesson

Truthiness vs bool, if and match

Rust has no truthy or falsy values: a condition must be a bool, and if and match are expressions whose branches share one type.

Core idea

if requires a bool, and every branch of an if or match expression must produce the same type.

JavaScript (Node.js) and Rust, side by side

JavaScript (Node.js) Truthiness sends 0 and NaN to "sold out", and loose equality makes 0 == "" true.
function stockLabel(count) {
  if (!count) return "sold out";   // 0, NaN, "" and undefined land here
  return count < 5 ? `only ${count} left` : "in stock";
}

console.log(stockLabel(0), "|", stockLabel(3), "|", stockLabel(12));
console.log(stockLabel(NaN), "|", stockLabel("7"));
console.log(Boolean("0"), Boolean([]), 0 == "", null == undefined);
Rust match with a range covers every u32, and the if expression yields a &str from either branch.
fn stock_label(count: u32) -> String {
    match count {
        0 => String::from("sold out"),
        1..=4 => format!("only {count} left"),
        _ => String::from("in stock"),
    }
}

fn main() {
    let count = 3;
    let urgent = if count > 0 && count < 5 { "yes" } else { "no" };
    println!("{} | {} | {}", stock_label(0), stock_label(count), stock_label(12));
    println!("urgent: {urgent}");
}
What changes
JavaScript (Node.js)Rust
if (!count) treats 0, NaN, "", null and undefined as false.if count is E0308; write count == 0 or text.is_empty().
0 == "" is true, which is why you use ===.There is one == and it never converts: comparing an integer with a &str does not compile.
a || b returns one of its operands.a || b takes two bool values and returns a bool.
switch falls through and need not cover every case.match arms never fall through and must cover every value.

Understand it

if (!count) mixes several questions: is it 0, NaN, "", null or undefined? Rust refuses to guess. if count with an integer is E0308, expected bool, found integer, so you write the question you mean: count == 0, text.is_empty(), value.is_none(). There is no == versus === either. == compares two values of compatible types through PartialEq and never converts, so 0 == "" does not compile.

if is an expression, which replaces both the statement form and the ternary. let urgent = if count > 0 && count < 5 { "yes" } else { "no" }; works because both branches are &str. If one branch yields a number and the other text, the expression has no single type and rustc rejects it. An if without else has type (), so it can only stand as a statement.

match is the tool for several cases of one value. Patterns can be literals, ranges such as 1..=4, or _ for everything else, and the compiler checks that the arms cover every possible value. For a u32, the arms 0, 1..=4 and _ are exhaustive, so no input can fall through, unlike a switch without default.

&& and || short-circuit as in JavaScript, but they accept and return only bool. There is no a || b default trick; that job belongs to Option methods such as unwrap_or, covered in the lesson on null and undefined.

The JavaScript (Node.js) habit, written in Rust

This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let count = 3;
    if count {
        println!("in stock");
    }
}

Practise this code in Playground ↗

Try it

Port the JavaScript fee shown at the top of solution.rs. A zero amount is free, members pay no fee, and other amounts pay a fee of 2 when the amount is at least 100 and 5 below that. Write every condition as an explicit bool. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including 0 and exactly 100. Printing a success message alone does not complete this lab.

Check your understanding

Why does let label = if count > 0 { count } else { "none" }; not compile?

Reveal the answer
  1. count > 0 is not a valid condition
  2. The branches produce different types: an integer and a &str
  3. if cannot appear on the right-hand side of let

An if expression has one type. Return count.to_string() from the first branch and String::from("none") from the second, or a number from both.

Go deeper

Common misconception: “if count works on numbers; Rust just treats 0 as false, like JavaScript.”

Rust has no truthiness. A condition must have type bool, so you compare explicitly, for example count != 0.

  1. Name each condition: stock_label asks three exact questions with patterns: is it 0, is it in 1..=4, or is it anything else.
  2. Check the types: Every match arm yields a String. The urgent expression yields a &str from both branches, so each expression has one type.
  3. Compare with evidence: Run it: sold out | only 3 left | in stock, then urgent: yes. Delete the _ arm and rustc reports E0004 for the values from 5 up to u32::MAX.

Transfer challenge: Add fn describe(text: &str) -> &'static str that returns "blank" for "" and for " ", and "text" otherwise. In JavaScript " " is truthy; decide which method expresses "blank" in Rust and why.

Connections

  • JavaScript functions vs fn: Typed parameters and tail expressions
  • Classes and objects vs structs: Data in structs, behaviour in impl blocks
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Truthiness vs bool, if and match: the same task in JavaScript (Node.js) and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Truthiness vs bool, if and match (courseId "rust-for-nodejs-developers", lessonId "node-truthiness-to-bool-and-match")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-truthiness-to-bool-and-match/
Goal: if requires a bool, and every branch of an if or match expression must produce the same type.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-truthiness-to-bool-and-match) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.