WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Intermediate · question 28 of 100

Can you explain the differences between synchronous and asynchronous JavaScript code?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, synchronous code is executed in a single thread, meaning that only one task can be processed at a time. Synchronous code blocks the execution of other code until it completes. Asynchronous code, on the other hand, allows other code to be executed while waiting for a particular task to complete.

Here are some examples to illustrate the difference between synchronous and asynchronous JavaScript code:

Synchronous code:

    console.log("Start");
    
    function wait(ms) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + ms);
    }
    
    wait(2000); // wait for 2 seconds
    
    console.log("End");

In this example, the wait function blocks the execution of other code until it completes. The code logs "Start", waits for 2 seconds, and then logs "End".

Asynchronous code:

    console.log("Start");
    
    setTimeout(function() {
        console.log("Hello, world!");
    }, 2000);
    
    console.log("End");

In this example, the setTimeout function allows other code to be executed while waiting for the specified delay to elapse. The code logs "Start", schedules the console.log("Hello, world!") function to be executed after 2 seconds, and then logs "End". After 2 seconds, the scheduled function is executed and logs "Hello, world!" to the console.

Another common example of asynchronous code in JavaScript is AJAX requests, which allow web pages to retrieve data from a server without blocking the execution of other code.

In summary, synchronous code in JavaScript blocks the execution of other code until it completes, while asynchronous code allows other code to be executed while waiting for a particular task to complete. Asynchronous code is commonly used for tasks that may take a long time to complete, such as network requests or user interactions.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics