JavaScript Execution & Asynchronicity.
Understanding Event Loop, Callbacks, and Browser APIs.
JavaScript is a crucial component in modern web development, enabling dynamic and interactive experiences. Understanding how JavaScript code gets executed, its asynchronous nature, event loop mechanism, callbacks, and interaction with browser APIs is fundamental for every web developer
JavaScript Code Execution
When a web page containing JS is loaded, the browser parses and executes the JS code.
The execution happens line by line, from top to bottom, in a single thread
Asynchronous JavaScript:
- Asynchronous programming in JavaScript allows non-blocking execution of code.
Ways to make JS code asynchronous:
a. Callbacks
b. Promises
c. Async/Await
Event Loop:
The event loop is a critical part of JS's concurrency model.
It manages the execution of asynchronous code and ensures that the program remains responsive.
It continuously checks the call stack and the callback queue.
When the call stack is empty, it takes a callback from the queue and pushes it onto the stack for execution.
- For Video Reference :- Youtube video
Callbacks :
A callback is a function passed as an argument to another function.
It gets executed after the completion of a particular task.
Commonly used in event handling, AJAX requests, and asynchronous operations.
function print(number, result) { console.log(`${number} is ${result}`); } function checkEvenOrOdd(number, callback) { const result = (number % 2 === 0) ? 'Even' : 'Odd'; callback(number, result); } checkEvenOrOdd(56, print); // 56 is Even
For Video Reference :- Youtube video
Promises :
Promises provide a cleaner way to deal with asynchronous code compared to callbacks. They represent a value that might be available now, in the future, or never.
const promiseA = new Promise((resolve, reject) => {
resolve(777);
});
// At this point, "promiseA" is already settled.
promiseA.then((val) => console.log("asynchronous logging has val:", val));
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777
Async / await :
Async/await is a modern way to work with asynchronous code. It allows you to write asynchronous code in a synchronous-like manner, making it easier to read and understand.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
async function fetchDataAsync() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchDataAsync();
Web Browser APIs:
Web Browser APIs are functionalities provided by browsers to interact with the browser environment.
Examples include:
a. DOM manipulation (document.getElementById(), etc.)
b. Fetch API (fetch())
c. Timers (setTimeout(), setInterval())
d. Geolocation API
e. Web Storage API (localStorage, sessionStorage)
Conclusion
This blog post provides a comprehensive overview of these fundamental concepts, empowering developers to write better JavaScript code and create dynamic web experiences.