DEV Community

Kiruthiga S
Kiruthiga S

Posted on

Javascript

1.Synchronous
Executes code one statement at a time, in the order they appear. The next statement waits until the current one finishes

console.log("Start");
console.log("Learning JavaScript");
console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:
Start
Learning JavaScript
End

2.Asynchronous
Allows to perform other tasks while waiting for a time-consuming operation (like API calls, timers, or file reading) to complete

console.log("Start");
setTimeout(() => {
    console.log("Hello");
}, 2000);
console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:
Start
End
Hello

3.Callback
A callback is a function passed as an argument to another function, which is executed after a task is completed

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}
function call() {
    console.log("Goodbye!");
}
greet("John", call);
Enter fullscreen mode Exit fullscreen mode

Output:
Hello John
Goodbye!

4.Callback Hell
Callback Hell occurs when multiple callbacks are nested inside each other, making the code difficult to read, understand, and maintain

setTimeout(() => {
    console.log("Step 1");
    setTimeout(() => {
        console.log("Step 2");
        setTimeout(() => {
            console.log("Step 3");
        }, 1000);
    }, 1000);
}, 1000);
Enter fullscreen mode Exit fullscreen mode

Output:
Step 1
Step 2
Step 3

5.Promise
A Promise is an object that represents the eventual success or failure of an asynchronous operation. It helps avoid callback hell

Promise has three states:
Pending – Initial state
Resolved – Operation successfully
Rejected – Operation failed

let promise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Data loaded successfully");
    } else {
        reject("Error loading data");
    }
});
promise
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.log(error);
    });
Enter fullscreen mode Exit fullscreen mode

Output:
Data loaded successfully

Top comments (0)