Ad space (banner)
🟨JavaScript Lessons
Lesson 29 / 69

Verifying Correctness with assert (Your First Step Into Testing)

In this lesson you'll learn a simple way to verify behavior using console.assert(), building the basic idea of testing. This is for people searching "JavaScript how to write tests" or "JavaScript assert usage."

console.assert(condition, message) displays a message only when the condition is false. It's the basic idea behind test code: automatically checking "does the function's result match what's expected." In real projects you'll use dedicated testing tools, but the underlying idea is the same as this assert — the habit of comparing "the expected result" against "the actual result" — and this is your first step toward that habit.

The sample code checks two conditions with console.assert(): one expecting that add(2, 3) should equal 5, and one deliberately wrong, expecting it should equal 6. Confirm the difference: the first condition is true, so nothing is displayed, while the second is false, so a message is shown.

A common beginner stumbling block is that console.assert() displays nothing when the condition is true, which can make it hard to tell "is this working, or did it not even run." When you want to confirm that a test is actually working, it helps to also try a condition you expect to fail on purpose.

In real development, dedicated testing tools like Jest or vitest are used to automate this kind of comparison between "the expected result" and "the actual result." Building a habit of writing tests for small, individual functions is essential for catching bugs early and building a codebase where you can add features with confidence.

Once you're ready to write tests more seriously, the next step is to adopt Node.js's built-in testing features, or a dedicated tool like Jest. The "compare the expected value against the actual value" mindset you learned here carries directly over.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)