Course contentsShow
← JavaScript
Lesson 1485 of 2,72332. JavaScript in the BrowserFree lesson

Console.assert for Inline Checks

Log errors only when conditions fail, creating lightweight assertions without throwing exceptions.

Console.assert for Inline Checks

You'll learn how to create lightweight condition checks that only log errors when something goes wrong, without stopping your code.

What Is Console.assert?

Think of console.assert() as a mini-alarm that only rings when things aren't as they should be. Unlike throwing errors that crash your program, assertions simply log a warning message when a condition fails, then let your code continue running.

The syntax is straightforward:

console.assert(condition, message);

If the condition is true, nothing happens. If it's false, the message gets logged to the console as an error.

When to Use Assertions

Assertions are perfect for sanity checks during development. They help you catch unexpected states without the ceremony of full error handling:

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

calculateDiscount(50, 20);   // Silent, all good
calculateDiscount(-10, 20);  // Logs: "Assertion failed: Price must be positive"
calculateDiscount(50, 150);  // Logs: "Assertion failed: Invalid percentage"

Why Not Just Throw Errors?

Assertions are non-blocking. Your code keeps running even when assertions fail, making them ideal for catching bugs during development without breaking the user experience. They're like warning lights on a dashboard—informative but not catastrophic.

You can also pass multiple arguments for richer logging:

console.assert(users.length > 0, "Empty user list", users);

Key Takeaway: Use console.assert() to validate assumptions and catch bugs early with minimal code, perfect for development-time checks that shouldn't halt execution.