- What is Synchronous JavaScript?
Synchronous means one task executes at a time, in order. The next task waits until the current task finishes.
console.log("First");
console.log("Second");
console.log("Third");
Output:
First
Second
Third
Each statement executes in order.
Real-life example: Standing in a queue. One person finishes before the next person is served.
- What is Asynchronous JavaScript?
Asynchronous operations allow JavaScript to continue doing other work while waiting for certain tasks to finish.
console.log("First");
setTimeout(() => {
console.log("Second");
}, 2000);
console.log("Third");
Output:
First
Third
Second
Why? setTimeout() schedules the callback to run later, so JavaScript continues with the next statement first.
- What is a Promise?
A Promise is a JavaScript object that represents the eventual success or failure of an asynchronous operation.
A Promise has three states:
Pending – Still waiting.
Fulfilled – Completed successfully.
Rejected – Failed.
Example:
let myPromise = new Promise((resolve, reject) => {
resolve("Task completed!");
});
myPromise.then((result) => {
console.log(result);
});
Output:
Task completed!
Top comments (0)