Callback hell
Callback Hell in JavaScript can be defined as the situation where we have nested callbacks(functions passed as arguments to other functions) which makes the code difficult to read and debug.
setTimeout(() => { console.log("analysis"); setTimeout(() => { console.log("planning"); setTimeout(() => { console.log("develop"); setTimeout(() => { console.log("testing"); setTimeout(() => { console.log("deployment"); }, 1000); }, 2000); }, 4000); }, 1000); }, 3000); Here, every setTimeout() is nested inside another callback. This makes the code difficult to read and maintain.
Solution to Callback Hell
Promises
Promises can help in avoiding the callback hell by providing the structured way to handle the asynchronous operations using the .then() method. Due to which the code becomes more readable by avoiding the deeply neseted callbacks.
function analysis() { return new Promise((res, rej) => { setTimeout(() => { console.log("analysis"); res(); }, 3000); }); } function planing() { return new Promise((res, rej) => { setTimeout(() => { console.log("planning"); res(); }, 1000); }); } function develop() { return new Promise((res, rej) => { setTimeout(() => { console.log("develop"); res(); }, 4000); }); } function testing() { return new Promise((res, rej) => { setTimeout(() => { console.log("testing"); rej("Testing rejected"); }, 2000); }); } function deployment() { return new Promise((res, rej) => { setTimeout(() => { console.log("deployment"); res(); }, 1000); }); } analysis() .then(() => planing()) .then(() => develop()) .then(() => testing()) .then(() => deployment()) .catch((reason) => console.log(reason)); output: analysis planning develop testing Testing rejected Async/Await approach
It is another way to avoid Callback Hell and make asynchronous code easier to read.
async function sdlc(){ try{ await analysis(); await planning(); await develop(); await testing(); await deployment(); } catch(err){ console.log(err); } sdlc(); Explanation
- async – Declares an asynchronous function. It always returns a Promise.
- await – Waits for the Promise to settle before moving to the next statement.
- try – Contains the code that may produce an error.
- catch – Handles a rejected Promise or an error.
async/await is built on Promises. It doesn't replace Promises; it provides a cleaner way to work with them.
Synchronous and Asynchronous
In JavaScript, synchronous functions execute sequentially and block further code until they finish, while asynchronous functions allow long-running tasks to run in the background without blocking the main thread.
Example of Synchronous
console.log("Analysis"); console.log("Planning"); console.log("Development"); console.log("Testing"); console.log("Deployment"); output: Analysis Planning Development Testing Deployment Example of Asynchronous
console.log("Analysis"); setTimeout(() => { console.log("Planning"); }, 3000); console.log("Development"); console.log("Testing"); console.log("Deployment"); Analysis Development Testing Deployment Planning Hoisting and Non-Hoisting
Hoisting is a JavaScript mechanism where variable and function declarations are processed before the code executes.
Example:
console.log(count); // Output: undefined var count = 5; console.log(count); // Output: 5 Non-Hoisting – let and const
non-hoisting (such as let, const, classes, and function expressions) cannot be safely used before the line where they are defined, throwing errors if accessed early.
console.log(score); // ReferenceError: Cannot access 'score' before initialization let score = 10; console.log(b); //ReferenceError: Cannot access 'b' before initialization const b = 20; Function Declarations
You can invoke a standard function anywhere in its scope, even above its definition.
greet(); // Output: "Hello!" function greet() { console.log("Hello!"); } Function Expressions and Arrow Functions
Only the variable binding is hoisted, not the function definition assigned to it.
sayHi(); // TypeError: sayHi is not a function (because var sayHi is undefined) var sayHi = () => console.log("Hi"); sayBye(); // ReferenceError: Cannot access 'sayBye' before initialization const sayBye = function() { console.log("Bye"); }; DOM(Document Object Model)
The DOM is a programming interface that allows JavaScript to access, modify, add, or delete HTML elements and CSS styles.
In simple words, DOM allows JavaScript to interact with an HTML webpage.
DOM Elements
DOM methods are used to access and manipulate HTML elements on web pages using JavaScript. These methods are used to select and make changes to certain types of elements.
getElementById():
This method selects based on the id attribute of an element on the page.
var element = document.getElementById("myElementId"); getElementsByClassName():
This method is used to select all elements belonging to a particular class.
var elements = document.getElementsByClassName("myClassName"); getElementsByTagName():
This method is used to select all elements with a specific tag.
var elements = document.getElementsByTagName("div"); querySelector() and querySelectorAll():
querySelector() selects the first element that matches a given CSS selector, while querySelectorAll() selects all matching elements.
var element = document.querySelector("#myElementId"); var elements = document.querySelectorAll(".myClassName"); DOM Manipulation
Web developers can perform DOM manipulation using JavaScript. This includes dynamically changing page content, adding new elements, removing existing elements, and updating style properties.
1.Changing HTML Content
We can change the content of an HTML element using innerHTML or textContent.
<h1 id="heading">Hello World</h1> <script> document.getElementById("heading").textContent = "Hello JavaScript"; </script> output: Hello JavaScript 2.Changing CSS Styles
We can also modify CSS styles using JavaScript.
<h1 id="heading">Hello JavaScript</h1> <script> const heading = document.getElementById("heading"); heading.style.color = "blue"; heading.style.backgroundColor = "yellow"; heading.style.fontSize = "30px"; </script> 3.Creating a New Element
We can add it to the page by creating a new HTML element.
var newElement = document.createElement("div"); newElement.innerHTML = "New Item"; document.body.appendChild(newElement); 4.Removing Elements
To remove an existing element, we must find the parent element of the element and then use the removeChild() method.
var elementToRemove = document.getElementById("myElementId"); elementToRemove.parentNode.removeChild(elementToRemove); DOM Events
Events are actions that happen in the browser, such as:
- click – When a user clicks an element.
- mouseover – When the mouse moves over an element.
- keydown – When a keyboard key is pressed.
- change – When an input value changes.
- submit – When a form is submitted.
<button id="btn">Click Me</button> <script> document.getElementById("btn").addEventListener("click", function() { alert("Button clicked!"); }); </script> Asynchronous Data Retrieval with Fetch API:
The Fetch API is a new asynchronous data retrieval method used in modern browsers. It attracts attention with its easier use and promise-based structure.
fetch("data.json") .then(response => response.json()) .then(data => { // Using data within the DOM }) .catch(error => { console.error("Error: ", error); }); Closure
Closure allows an inner function to access the variables of its outer function even after the outer function has completed execution.
function bank() { let balance = 1000; return { deposit: function(amount) { balance = balance + amount; console.log("Deposited:", amount); console.log("Balance:", balance); }, withdraw: function(amount) { balance = balance - amount; console.log("Withdrawn:", amount); console.log("Balance:", balance); }, checkBalance: function() { console.log("Current Balance:", balance); } }; } const myAccount = bank(); myAccount.checkBalance(); myAccount.deposit(500); myAccount.withdraw(200); myAccount.checkBalance(); output: Current Balance: 1000 Deposited: 500 Balance: 1500 Withdrawn: 200 Balance: 1300 Current Balance: 1300 How does Closure work here?
- bank() is the outer function.
- balance is a local variable inside bank().
- deposit, withdraw, and checkBalance are inner functions.
- These inner functions remember and access the same balance variable even after bank() finishes executing.
Important: You cannot directly access the balance variable:
