Checking with console.assert
Learn to log an error when a condition fails with console.assert.
Checking with console.assert
console.assert(condition, message) prints message as an error when condition is false; it does nothing when true. This is useful for checking assumptions in your code.
For example, assume a function expects a positive number. With console.assert(value > 0, "value must be positive") you get a warning when this expectation breaks. Such a check is called an assertion.
Where are assertions used?
Assertions check conditions that must hold for the rest of the code to work correctly. You can verify that a loop index stays in bounds or that a function argument has the expected type.
But assertions are not for controlling normal flow; they exist to surface bugs temporarily. Cleaning up unnecessary assertions before going to production is a good habit.
Exercise Check a variable with console.assert
Define a function called divide(a, b). It should check that b is not 0 with console.assert(b !== 0, "b cannot be zero"). Then it should return a / b. Finally call divide(10, 2).
Show example solution
function divide(a, b) {
console.assert(b !== 0, "b cannot be zero");
return a / b;
}
divide(10, 2);
Test yourself
-
When does console.assert(cond, msg) print the message?
- When the condition is true
- Always
- Never
- When the condition is false
Show answer
When the condition is false — Correct. Assert warns when the condition fails.
-
Match the usage
- console.assert(true, msg)
- Prints nothing
- console.assert(false, msg)
- Prints the message as an error
- console.assert(x > 0, ...)
- Warns when x is not positive
- console.log(msg)
- Always prints the message
-
Complete the console.assert call
function checkAge(age) { console.assert(____, "age cannot be negative"); }Show answer
function checkAge(age) { console.assert(age >= 0, "age cannot be negative"); }