Synchronous Callbacks

Introduction

A synchronous callback is a callback function that is executed immediately during the execution of another function. The program waits for the callback to finish before moving on to the next line of code.

Unlike asynchronous callbacks, synchronous callbacks do not involve timers, file operations, API requests, or other background tasks. They execute in sequence, making the flow of execution simple and predictable.

Many built-in JavaScript methods such as forEach(), map(), filter(), find(), reduce(), and sort() use synchronous callbacks.

For automation engineers, synchronous callbacks are commonly used for processing test data, iterating through collections, filtering API responses, transforming JSON objects, validating data, and performing calculations before executing automation steps.

In this tutorial, you’ll learn what synchronous callbacks are, how they work, and how they are used in Node.js.


What is a Synchronous Callback?

A synchronous callback is a callback function that executes immediately while the calling function is still running.

The next statement in the program is executed only after the callback has finished.


Why Use Synchronous Callbacks?

Synchronous callbacks help developers:

  • Process data immediately.

  • Keep code simple.

  • Improve code reusability.

  • Perform calculations.

  • Iterate through collections.

  • Transform data.

  • Validate input values.


How Synchronous Callbacks Work

The execution flow is:

  1. A function receives a callback.

  2. The callback is executed immediately.

  3. The callback finishes.

  4. The remaining program continues.

Everything happens in a single execution flow.


Syntax

function process(callback) {

    callback();

}

process(function () {

    console.log(
        "Callback executed."
    );

});

Example 1: Basic Synchronous Callback

function display(callback) {

    console.log(
        "Start"
    );

    callback();

    console.log(
        "End"
    );

}

display(function () {

    console.log(
        "Processing..."
    );

});

Sample Output

Start
Processing...
End

The callback runs immediately between the two console.log() statements.


Example 2: Using forEach()

const numbers =
    [10, 20, 30];

numbers.forEach(function (number) {

    console.log(number);

});

Sample Output

10
20
30

The callback is executed once for every element in the array.


Example 3: Using map()

const numbers =
    [1, 2, 3];

const result =
    numbers.map(function (number) {

        return number * 2;

    });

console.log(result);

Sample Output

[ 2, 4, 6 ]

Example 4: Using filter()

const ages =
    [16, 20, 15, 25];

const adults =
    ages.filter(function (age) {

        return age >= 18;

    });

console.log(adults);

Sample Output

[ 20, 25 ]

Example 5: Using sort()

const numbers =
    [5, 2, 9, 1];

numbers.sort(function (a, b) {

    return a - b;

});

console.log(numbers);

Sample Output

[ 1, 2, 5, 9 ]

Automation Testing Examples

Synchronous callbacks are frequently used in automation frameworks for processing collections and validating data.

Playwright Example

Process page names.

const pages =
    ["Home", "Login", "Profile"];

pages.forEach(function (page) {

    console.log(
        "Testing " + page
    );

});

Sample Output

Testing Home
Testing Login
Testing Profile

Selenium Example

Validate browser names.

const browsers =
    ["Chrome", "Firefox"];

browsers.forEach(function (browser) {

    console.log(browser);

});

Sample Output

Chrome
Firefox

Cypress Example

Convert test names to uppercase.

const tests =
    ["login", "logout"];

const result =
    tests.map(function (test) {

        return test.toUpperCase();

    });

console.log(result);

Sample Output

[ 'LOGIN', 'LOGOUT' ]

API Testing Example

Filter successful response codes.

const statusCodes =
    [200, 404, 201, 500];

const success =
    statusCodes.filter(function (code) {

        return code < 300;

    });

console.log(success);

Sample Output

[ 200, 201 ]

Data-Driven Testing Example

Display employee names.

const employees =
    ["John", "Sara", "David"];

employees.forEach(function (employee) {

    console.log(employee);

});

Sample Output

John
Sara
David

Common Uses of Synchronous Callbacks

Synchronous callbacks are commonly used for:

  • Array iteration.

  • Data transformation.

  • Filtering data.

  • Sorting collections.

  • Searching arrays.

  • Data validation.

  • Calculations.

  • Formatting values.

  • Processing JSON objects.

  • Test data preparation.


Synchronous Callback vs Asynchronous Callback

FeatureSynchronous CallbackAsynchronous Callback
ExecutionImmediatelyLater
Blocks executionYesNo
Waits for completionYesNo
Used withArray methodsTimers, APIs, files
Execution orderSequentialEvent-driven

Common Mistakes

Assuming All Callbacks Are Asynchronous

Many developers think every callback is asynchronous, but callbacks used with methods like forEach() and map() are synchronous.


Performing Long-Running Tasks

Lengthy operations inside synchronous callbacks can block program execution.


Modifying Data Unnecessarily

Avoid changing the original data unless it is required.


Best Practices

  • Keep callbacks short and focused.

  • Use built-in array methods when possible.

  • Avoid heavy computations inside callbacks.

  • Write reusable callback functions.

  • Use descriptive parameter names.

  • Prefer map() for transformations and filter() for filtering.

  • Keep callback logic easy to read.


Conclusion

Synchronous callbacks execute immediately and are an essential part of JavaScript programming. They are commonly used with array methods to process, transform, filter, and validate data in a simple and predictable manner.

For automation engineers, synchronous callbacks are especially useful when preparing test data, validating API responses, processing JSON objects, and iterating through collections before performing automation steps. Understanding synchronous callbacks provides a strong foundation before learning asynchronous callbacks, Promises, and async/await.


Frequently Asked Questions (FAQs)

What is a synchronous callback?

A synchronous callback executes immediately while the calling function is still running.


Do synchronous callbacks block execution?

Yes. The program waits until the callback finishes before moving to the next statement.


Which JavaScript methods use synchronous callbacks?

Methods such as forEach(), map(), filter(), find(), reduce(), and sort() use synchronous callbacks.


Are synchronous callbacks useful in automation testing?

Yes. They are commonly used for processing test data, filtering API responses, formatting values, and validating data.


What is the difference between synchronous and asynchronous callbacks?

Synchronous callbacks execute immediately and block execution, whereas asynchronous callbacks execute later after an operation or event completes.


Key Takeaways

  • Synchronous callbacks execute immediately.

  • They block execution until they finish.

  • Built-in array methods use synchronous callbacks.

  • They are useful for processing and transforming data.

  • Synchronous callbacks provide predictable execution order.

  • They are widely used in data validation and formatting.

  • Automation frameworks use them for preparing test data and processing API responses.

  • Keep callback functions small and reusable.

  • Avoid heavy processing inside synchronous callbacks.

  • Understanding synchronous callbacks is essential before learning asynchronous programming.