Course contentsShow
← Web Development
Lesson 2192 of 2,98240. Browser DevTools Deep DiveFree lesson

Console.assert() for Runtime Checks

Add inline assertions that log errors only when conditions fail during development.

Console.assert() for Runtime Checks

You'll learn how to embed lightweight, conditional error messages that only fire when something goes wrong, keeping your console clean during normal execution.

What Is Console.assert()?

console.assert() is a debugging tool that tests a condition and only logs an error message if the condition is false. Think of it like a silent guard at a gate: if everything checks out, it says nothing. If something's wrong, it raises an alarm.

Unlike console.log(), which always outputs, assert() remains invisible when your code behaves correctly. This makes it perfect for sanity checks during development without cluttering your console.

How It Works

The syntax is straightforward:

console.assert(condition, message, ...optionalData);

If condition evaluates to true, nothing happens. If false, DevTools logs an assertion failed error with your message.

Practical Examples

Check function inputs:

function calculateDiscount(price, percentage) {
  console.assert(price > 0, 'Price must be positive', price);
  console.assert(percentage >= 0 && percentage <= 100, 'Invalid percentage', percentage);
  
  return price * (1 - percentage / 100);
}

calculateDiscount(100, 20);  // Silent, all good
calculateDiscount(-50, 20);  // Assertion failed: Price must be positive -50

Validate state:

const user = fetchUser();
console.assert(user !== null, 'User should exist at this point');
console.assert(user.roles.length > 0, 'User must have at least one role', user);

When to Use It

  • Development-time validation of assumptions
  • Internal consistency checks that should never fail in correct code
  • Quick debugging without writing full if statements

Remember: assertions aren't replacements for proper error handling in production—they're development aids.

Key Takeaway:
Use console.assert() to add invisible runtime checks that only shout when your assumptions break, keeping your debugging output signal-rich and noise-free.