Back to JavaScript
2025-12-146 min read

Assertions (JavaScript)

Learn Assertions (JavaScript) step by step with clear examples and exercises.

Title: Assertions in JavaScript - A full guide

Why This Matters

Assertions are a crucial part of JavaScript programming, helping developers ensure their code runs as expected and catches errors early. This guide will delve into the world of assertions, explaining how they work, common mistakes to avoid, and providing practice questions for solidifying your understanding.

Prerequisites

Before diving into assertions, it's essential to have a good grasp of JavaScript fundamentals:

  1. Understanding variables, data types, and operators
  2. Familiarity with control structures like loops and conditional statements
  3. Knowledge of functions and function calls
  4. Basic understanding of error handling (try-catch)
  5. Comfortable working with Node.js and its core modules
  6. Understanding object properties and methods
  7. Experience with unit testing frameworks such as Jest or Mocha (optional but recommended for advanced topics)

Core Concept

What are Assertions?

Assertions are a way to check if a condition is true within your code, helping you ensure that the program behaves as intended. They can be used to verify function arguments, validate return values, and test the state of an application at various stages.

Built-in Assertion Functions in JavaScript

JavaScript provides several built-in assertion functions:

  1. assert(): This is a part of Node.js core module. It throws an error if the provided condition is false, making it useful for unit testing.
const assert = require('assert');

assert(3 > 2); // No error thrown since the condition is true
assert(2 > 3); // Error thrown because the condition is false
  1. console.assert(): This function is also a part of Node.js core module but writes to the console instead of throwing an error. It's useful for logging assertions during development.
console.assert(3 > 2, 'Three is greater than two'); // Outputs: Three is greater than two (if condition is true)
console.assert(2 > 3, 'Two is greater than three'); // Outputs: TypeError: assertion failed: Two is greater than three (if condition is false)

Writing Custom Assertions

You can also create your own assertion functions to suit specific needs. Here's an example of a custom assertion that checks if two arrays are equal:

function assertArraysEqual(arr1, arr2) {
const arr1String = JSON.stringify(arr1);
const arr2String = JSON.stringify(arr2);

if (arr1String !== arr2String) {
throw new Error(`Expected [${arr1}] to be equal to [${arr2}]`);
}
}

const arr1 = [1, 2, 3];
const arr2 = [1, 2, 4];
assertArraysEqual(arr1, arr2); // Throws an error since the arrays are not equal

Advanced Custom Assertions

For more complex assertions, you can use functions like Array.isArray(), Object.keys(), and Object.values(). Here's an example of a custom assertion that checks if a provided object has all required properties:

function assertObjectProperties(obj, requiredProperties) {
const missingProperties = requiredProperties.filter((property) => !Object.prototype.hasOwnProperty.call(obj, property));

if (missingProperties.length > 0) {
throw new Error(`Missing properties: ${missingProperties.join(', ')}`);
}
}

const user = { name: 'John' };
assertObjectProperties(user, ['name', 'age']); // No error thrown since all required properties are present

Worked Example

Let's create a function that calculates the factorial of a number and use assertions to ensure it works correctly:

function factorial(n) {
if (n < 0) {
throw new Error('Factorial is not defined for negative numbers');
}

let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}

assert(result >= 1, `Factorial of ${n} should be a positive number`);
return result;
}

const factorialResult = factorial(5); // No error thrown since the function works correctly
console.log(factorialResult); // Outputs: 120

In this example, we've added an assertion to check if the calculated factorial is a positive number. If not, an error will be thrown.

Common Mistakes

  1. Not checking for edge cases: Make sure to test your assertions with different inputs, including edge cases like zero or negative numbers.
  2. Using assertions for flow control: Assertions are not meant to be used for controlling the flow of your program. Instead, use them to verify the correctness of your code.
  3. Ignoring errors: Don't ignore errors thrown by assertions. They indicate a problem in your code that needs to be addressed.
  4. Not handling exceptions: If an error is thrown within an assertion, it should be handled appropriately to avoid crashing the entire application.
  5. Overusing assertions: While assertions are useful for validating your code, overuse can lead to unnecessary errors and make debugging more difficult.
  6. Not documenting assertions: Properly documenting your assertions helps others understand why they were implemented and what they're checking for.

Common Mistakes (Continued)

  1. Assuming all inputs are valid: Always validate input data before using it in your assertions to avoid unexpected errors.
  2. Not testing assertion functions: Just like any other function, assertion functions should be tested to ensure they work as intended.
  3. Ignoring assertion failures: Failing assertions indicate problems that need to be addressed. Don't ignore them and make sure to fix the underlying issues.
  4. Not using a unit testing framework: While it's possible to write tests manually, using a unit testing framework like Jest or Mocha can help streamline your testing process and catch errors more efficiently.

Practice Questions

  1. Write an assertion function to check if two strings are anagrams of each other.
  2. Create a custom assertion function that checks if a given number is prime.
  3. Use assertions to validate the arguments passed to a function that calculates the area of a rectangle.
  4. Implement a custom assertion function that ensures a provided object has all required properties and their values meet certain conditions.
  5. Write an assertion function to check if a given array contains only unique elements.
  6. Create a custom assertion function that checks if a provided object's properties follow a specific format (e.g., keys are all lowercase, values are numbers).
  7. Implement a unit test for the factorial function using a unit testing framework like Jest or Mocha.
  8. Write an assertion function to check if a given string is a palindrome.
  9. Create a custom assertion function that checks if a provided array is sorted in ascending order.
  10. Implement a unit test for the sorting function using a unit testing framework like Jest or Mocha.

FAQ

  1. Why should I use assertions in my code?
  • Assertions help catch errors early, making debugging easier and your code more reliable. They also serve as documentation for your code's intended behavior.
  1. What's the difference between assert() and console.assert()?
  • assert() throws an error if the provided condition is false, while console.assert() writes to the console instead of throwing an error.
  1. Can I create my own assertion functions in JavaScript?
  • Yes! Custom assertion functions can be created to suit specific needs and validate custom conditions.
  1. What happens when an error is thrown by an assertion function?
  • If an error is thrown by an assertion, it will be handled according to the error handling mechanism of your JavaScript environment (e.g., Node.js or a browser). In most cases, this means the execution of the current script or function will stop, and the error message will be logged or displayed.
  1. How can I handle exceptions in custom assertion functions?
  • To handle exceptions in custom assertion functions, you can wrap the assertion code within a try-catch block. This allows you to catch any errors that might occur during the assertion and handle them appropriately.
  1. Are there any best practices for using assertions in my code?
  • Yes! Some best practices include:
  • Using assertions to validate input arguments, return values, and internal state of functions and modules.
  • Writing clear and descriptive error messages that help you and others understand the cause of the error.
  • Avoiding overuse of assertions, as too many can make debugging more difficult.
  • Handling exceptions in custom assertion functions to prevent crashes.
  • Properly documenting your assertions helps others understand why they were implemented and what they're checking for.
  1. What is the difference between an assertion and a unit test?
  • An assertion is a function that checks if a specific condition is true, whereas a unit test is a piece of code designed to verify whether a larger section of code (such as a function or module) behaves as expected under various conditions. While assertions are used within the codebase for validation, unit tests are typically run separately to ensure the correct functioning of the code before it's deployed.
Assertions (JavaScript) | JavaScript | XQA Learn