🚀 Top 10 Most Asked JavaScript Interview Questions (with Answers) If you're preparing for a frontend or full-stack interview, these JavaScript questions come up all the time. Let’s make sure you’re ready 💪 💡 1. Difference between var, let, and const var → function-scoped, can be redeclared. let → block-scoped, can be reassigned. const → block-scoped, cannot be reassigned. 💡 2. What is a Closure? A closure allows an inner function to access variables from an outer function even after it’s returned. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 💡 3. What is Hoisting? Hoisting moves variable & function declarations to the top of their scope. console.log(a); // undefined var a = 5; 💡 4. Difference between == and === == → compares values after type conversion. === → compares values & types. ✅ 5 == '5' → true ❌ 5 === '5' → false 💡 5. What are Promises? Promises handle asynchronous operations in JS. fetch('https://api.example.com') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); 💡 6. What is async/await? A cleaner way to work with Promises. async function getData() { try { const res = await fetch('https://api.example.com'); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 💡 7. Event Bubbling vs Capturing Bubbling: Event travels child → parent. Capturing: Event travels parent → child. Use { capture: true } to enable capturing. 💡 8. Difference between null and undefined undefined → variable declared but not assigned. null → intentional absence of value. 💡 9. What is the Event Loop? It continuously checks the call stack & callback queue to execute asynchronous code efficiently. 💡 10. What is this in JavaScript? this refers to the object that is executing the current function. const user = { name: 'John', greet() { console.log(this.name); } }; user.greet(); // John 🔥 Pro Tip: Understand these concepts deeply, not just by reading — code small examples for each! #JavaScript #AppDevelopment #CodingInterview #Frontend #CareerTips #Programming #TechLearning
Top 10 JavaScript Interview Questions with Answers
More Relevant Posts
-
12 JavaScript Interview Questions - Concise 2-Point Answers 𝟭. 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻 & 𝗠𝗲𝗺𝗼𝗿𝘆 𝗟𝗲𝗮𝗸𝘀 - GC: Automatic mark-and-sweep algorithm removes unreachable objects from memory periodically - Leaks: Forgotten timers, closures holding references, global variables, detached DOM nodes prevent cleanup 𝟮. 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) - What: Period between scope entry and let/const declaration where access throws ReferenceError - Why: Catches errors early, prevents usage before initialization, ensures consistent behavior 𝟯. 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻 - How: Single listener on parent handles child events via event.target and bubbling - Benefits: Less memory, better performance, auto-handles dynamic elements 𝟰. 𝗪𝗲𝗮𝗸𝗠𝗮𝗽 & 𝗪𝗲𝗮𝗸𝗦𝗲𝘁 - What: Collections with weak object references allowing garbage collection - Use: Private data, DOM metadata, caching without memory leaks 𝟱. 𝗻𝗲𝘄 𝗞𝗲𝘆𝘄𝗼𝗿𝗱 - Process: Creates object → sets prototype → binds this → executes constructor - Returns: New instance or explicit object return 𝟲. 𝗖𝘂𝗿𝗿𝘆𝗶𝗻𝗴 & 𝗣𝗮𝗿𝘁𝗶𝗮𝗹 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻 - Currying: f(a,b,c) → f(a)(b)(c) - chains single-argument functions - Uses: Reusable configs, preset parameters, functional composition 𝟳. 𝗢𝗯𝗷𝗲𝗰𝘁.𝗳𝗿𝗲𝗲𝘇𝗲/𝘀𝗲𝗮𝗹/𝗽𝗿𝗲𝘃𝗲𝗻𝘁𝗘𝘅𝘁𝗲𝗻𝘀𝗶𝗼𝗻𝘀 - freeze: Fully immutable (no add/delete/modify) - seal: No add/delete, allows modify | preventExtensions: Only blocks adding 𝟴. 𝗣𝗿𝗼𝘅𝘆 & 𝗥𝗲𝗳𝗹𝗲𝗰𝘁 - Proxy: Intercepts operations (get/set/delete) with custom traps for validation/logging - Reflect: Default operation methods used inside proxy handlers 𝟵. 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝘃𝘀 𝗔𝗻𝗶𝗺𝗮𝘁𝗶𝗼𝗻 𝗙𝗿𝗮𝗺𝗲 - Microtasks: Execute after script, before render (Promises) - high priority - Animation Frames: Execute before repaint, synced to refresh rate 𝟭𝟬. 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻 - What: Cache function results by arguments to avoid recalculation - How: Store in Map/object, return cached or compute and cache 𝟭𝟭. 𝗧𝗮𝗶𝗹 𝗖𝗮𝗹𝗹 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻 - What: Reuses stack frame for tail-position calls preventing overflow - JS Support: Only Safari - V8/SpiderMonkey don't support it 𝟭𝟮. 𝗪𝗲𝗯 𝗪𝗼𝗿𝗸𝗲𝗿𝘀 - What: Background threads for JS, communicate via postMessage - Uses: Heavy computations, prevent UI blocking, parallel processing ----------------------------------- Join devs on 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗖𝗶𝗿𝗰𝗹𝗲 𝗯𝘆 𝗦𝗮𝗸𝘀𝗵𝗶 → https://lnkd.in/d45J2fuv 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗧𝗼𝗱𝗮𝘆 → https://lnkd.in/dK94iu7Y Follow Sakshi Gawande for more such content 💓
To view or add a comment, sign in
-
✅ *Advanced JavaScript Interview Questions with Answers* 💼🧠 *1. What is a closure in JavaScript?* A *closure* is a function that has access to its outer function's variables, even after the outer function has returned. ```js function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 ``` *2. Explain event delegation.* Event delegation is a technique where you attach a single event listener to a parent element to handle events on its child elements using `event.target`. *3. What is the difference between == and ===?* - `==` checks for value equality (type coercion allowed). - `===` checks for both value and type (strict equality). ```js '5' == 5 // true '5' === 5 // false ``` *4. What is the "this" keyword?* `this` refers to the object that is executing the current function. In arrow functions, `this` is lexically bound (based on where it's defined). *5. What are Promises?* Promises handle asynchronous operations. They have 3 states: *pending, resolved, rejected*. ```js const p = new Promise((resolve, reject) => { resolve("Success"); }); p.then(console.log); ``` *6. Explain async/await.* Syntactic sugar over Promises for better readability in async code. ```js async function fetchData() { const res = await fetch(url); const data = await res.json(); } ``` *7. What is hoisting?* Variables and function declarations are moved to the top of their scope before code execution. ```js console.log(a); // undefined var a = 5; ``` *8. What are arrow functions and how do they differ?* Arrow functions are shorter and do not have their own `this`, `arguments`, or `super`. ```js const add = (a, b) => a + b; ``` *9. What is the event loop?* The event loop handles asynchronous callbacks and ensures non-blocking behavior in JS by placing them in the task queue after the call stack is clear. *10. What are IIFEs (Immediately Invoked Function Expressions)?* Functions that run as soon as they are defined. ```js (function() { console.log("Runs immediately"); })(); ```
To view or add a comment, sign in
-
Most frequently asked 21 programs in L1 & L2 javascript interviews Get all 232 interview ques & ans for free on interviewdepth.com 1. Program to find longest word in a given sentence ? 2. How to check whether a string is palindrome or not ? 3. Write a program to remove duplicates from an array ? 4. Program to find Reverse of a string without using built-in method ? 5. Find the max count of consecutive 1’s in an array ? 6. Find the factorial of given number ? 7. Given 2 arrays that are sorted [0,3,4,31] and [4,6,30]. Merge them and sort [0,3,4,4,6,30,31] ? 8. Create a function which will accepts two arrays arr1 and arr2. The function should return true if every value in arr1 has its corresponding value squared in array2. The frequency of values must be same. 9. Given two strings. Find if one string can be formed by rearranging the letters of other string. 10. Write logic to get unique objects from below array ? I/P: [{name: "sai"},{name:"Nang"},{name: "sai"},{name:"Nang"},{name: "111111"}]; O/P: [{name: "sai"},{name:"Nang"}{name: "111111"} 11. Write a JavaScript program to find the maximum number in an array. 12. Write a JavaScript function that takes an array of numbers and returns a new array with only the even numbers. 13. Write a JavaScript function to check if a given number is prime. 14. Write a JavaScript program to find the largest element in a nested array. [[3, 4, 58], [709, 8, 9, [10, 11]], [111, 2]] 15. Write a JavaScript function that returns the Fibonacci sequence up to a given number of terms. 16. Given a string, write a javascript function to count the occurrences of each character in the string. 17. Write a javascript function that sorts an array of numbers in ascending order. 18. Write a javascript function that sorts an array of numbers in descending order. 19. Write a javascript function that reverses the order of words in a sentence without using the built-in reverse() method. 20. Implement a javascript function that flattens a nested array into a single-dimensional array. 21. Write a function which converts string input into an object ("a.b.c", "someValue"); {a: {b: {c: "someValue"}}} #javascriptdeveloper #reactjs #reactjsdeveloper #angular#angulardeveloper #vuejs #vuejsdeveloper #javascript
To view or add a comment, sign in
-
🚀 Master JavaScript Interviews — A Practical Question List Here’s a fresh and concise list of JavaScript interview questions 👇 🟢 Foundation Level 1. Explain how JavaScript is both dynamically and weakly typed. 2. What’s the difference between declaring a variable and assigning a value to it? 3. How do let and const behave inside and outside of blocks? 4. Why is using var generally discouraged in modern code? 5. What are template literals, and how can they simplify string concatenation? 6. How does JavaScript handle type coercion in expressions? 7. What’s the difference between null, undefined, and NaN? 8. How can you safely copy an object without referencing the original? 9. Explain how the spread operator works with arrays and objects. 10. How do default parameters work in function definitions? 11. What happens if you call a function before it’s defined? 12. Give an example of an immediately invoked function expression (IIFE). 🟡 Intermediate Level 13. How does the JavaScript event loop actually schedule tasks? 14. What problem do Promises solve compared to traditional callbacks? 15. How does async/await simplify asynchronous flow, and what are its pitfalls? 16. What is a closure, and how can it be used to create private state? 17. How does this behave differently in arrow functions vs. regular functions? 18. Why might you use .bind() in your code, and what problem does it solve? 19. What are higher-order functions, and can you write one from scratch? 20. Describe how destructuring improves code readability. 21. What is prototypal inheritance, and how does it differ from classical inheritance? 22. How can you convert an array-like object (like arguments) into a true array? 23. What is the difference between synchronous and asynchronous execution in JS? 24. How does JavaScript handle exceptions inside async functions? 🔴 Advanced Level 25. How does event delegation reduce memory usage in web applications? 26. What are WeakMap and WeakSet, and when would you use them? 27. How does JavaScript handle memory leaks, and how can you detect them? 28. How does garbage collection work under the hood? 29. How would you implement throttling or debouncing for user input? 30. Explain the concept of currying and provide a use case. 31. What are generators and iterators, and how are they useful? 32. How do Web Workers help improve performance? 33. What techniques can you use to optimize a large JavaScript bundle? 34. How would you handle deep object comparison efficiently? 👉 Follow Sharad kumar for daily doses of tech wisdom, corporate realities, and relatable IT life. 🚀 #ReactJS #Angular #Nodejs #Frontend #InterviewPreparation #JavaScript #FullStack #WebDevelopment #SoftwareEngineer #Learning #Hiring #Jobs #FresherJobs #TechTalks
To view or add a comment, sign in
-
🚀 Top 10 Advanced JavaScript Interview Questions & Answers 💼💡 If you’re preparing for frontend or full-stack interviews, mastering these JavaScript concepts is a must! 1️⃣ Closure A closure is when a function remembers its lexical scope even after the outer function has executed. Code: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Event Delegation Attach a single event listener to a parent element to manage events of its child elements using event.target. 3️⃣ == vs === == → checks value (performs type coercion) === → checks value + type (strict equality) Code: '5' == 5 // true '5' === 5 // false 4️⃣ The “this” Keyword Refers to the object executing the current function. In arrow functions, this is lexically bound (taken from the outer scope). 5️⃣ Promises Used to handle asynchronous operations. Code: const p = new Promise((resolve) => resolve("Success")); p.then(console.log); 6️⃣ Async / Await Syntactic sugar over Promises for cleaner async code. Code: async function fetchData() { const res = await fetch(url); const data = await res.json(); } 7️⃣ Hoisting Variables and functions are moved to the top of their scope during compilation. Code: console.log(a); // undefined var a = 5; 8️⃣ Arrow Functions Shorter syntax, no own this, arguments, or super. Code: const add = (a, b) => a + b; 9️⃣ Event Loop Manages asynchronous tasks — ensures non-blocking behavior by moving callbacks from the task queue to the call stack once it’s empty. 🔟 IIFE (Immediately Invoked Function Expression) Executes immediately after its definition. Code: (function() { console.log("Runs immediately"); })(); 💬 These are must-know concepts for any JavaScript developer aiming to ace technical interviews and build a strong foundation. 💻 Keep practicing, keep learning — and you’ll nail your next interview! ⚡ #JavaScript #WebDevelopment #Frontend #MERN #InterviewPreparation #Coding #Developers
To view or add a comment, sign in
-
✅ JavaScript Objects – Interview Questions & Answers ⚡🧠 🔹 1. What is an object in JavaScript? An object is a collection of key-value pairs used to store related data and functionality. Example: const user = { name: "Alice", age: 25 }; 🔹 2. How do you access object properties? Using dot or bracket notation: user.name // "Alice" user["age"] // 25 🔹 3. How can you loop through an object? Use for...in or Object.keys()/Object.entries(): for (let key in user) { console.log(key, user[key]); } 🔹 4. Difference between Object.freeze() and Object.seal()? ⦁ freeze() prevents any change (no adding, deleting, or modifying properties). ⦁ seal() allows value changes, but not adding/removing keys. 🔹 5. How do you clone an object? const clone = {...user }; // or const copy = Object.assign({}, user); 🔹 6. What is this inside an object? this refers to the object itself in method context. const person = { name: "Bob", greet() { return `Hi, I’m ${this.name}`; } }; 🔹 7. How do prototypes relate to objects? Every JS object has a hidden [[Prototype]]. It lets objects inherit properties from others. 🔹 8. What is a constructor function? A function used to create multiple similar objects: function User(name) { this.name = name; } const u = new User("Tom"); 🔹 9. What's the difference between Object.create() and new keyword? ⦁ Object.create(proto) creates an object with the given prototype. ⦁ new invokes a constructor function to initialize objects. 🔹 10. How do you check if a property exists in an object? "name" in user // true user.hasOwnProperty("age") // true
To view or add a comment, sign in
-
🚀 Deep Dive into the JavaScript Event Loop – Interview Ready! One of the most common questions in JavaScript interviews is: “Explain the Event Loop.” Let’s break it down in a way that makes you confident in answering. 1️⃣ What is the Event Loop? JavaScript is single-threaded, which means it can execute only one piece of code at a time. The Event Loop is a mechanism that allows JS to handle asynchronous operations like I/O, timers, and network requests without blocking the main thread. It continuously checks the Call Stack and Task Queues to decide what to execute next. 2️⃣ Key Components Call Stack – Where functions are executed in LIFO order. Heap – Memory allocation for objects. Task Queues – Holds callbacks waiting to be executed: Macro-tasks (Task Queue): setTimeout, setInterval, I/O callbacks. Micro-tasks (Microtask Queue): Promises, process.nextTick (Node.js), queueMicrotask. 3️⃣ Event Loop Phases (Node.js Perspective) The Node.js Event Loop has 6 main phases: 1. Timers Phase – Executes callbacks scheduled by setTimeout and setInterval. 2. I/O Callbacks Phase – Executes deferred I/O callbacks. 3. Idle, Prepare Phase – Internal phase used by Node.js. 4. Poll Phase – Retrieves new I/O events and executes their callbacks. 5. Check Phase – Executes callbacks scheduled by setImmediate. 6. Close Callbacks Phase – Executes close event callbacks like socket.on('close', …). 4️⃣ Microtasks vs Macrotasks Microtasks run after the current operation and before the next event loop tick. Macrotasks run in the next event loop iteration. > Example Execution Order: setTimeout(() => console.log("Timer"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("Sync"); Output: Sync Promise Timer 5️⃣ Quick Interview Tip Always clarify browser vs Node.js differences. Remember Microtasks > Macrotasks in execution order. Mention that event loop keeps JS non-blocking despite being single-threaded. 💡 Pro Tip: Visualizing the Event Loop as a continuous loop checking the call stack and task queues makes it easier to reason about async behavior in JS. #JavaScript #NodeJS #WebDevelopment #EventLoop #AsyncJS #Frontend #Backend #FullStack #CodingInterviews #TechTips #Programming #SoftwareEngineering #Developer #100DaysOfCode #TechCareer #CodeNewbie
To view or add a comment, sign in
-
-
✅ Advanced JavaScript Interview Questions with Answers 💼🧠 1. What is a closure in JavaScript? A closure is a function that has access to its outer function's variables, even after the outer function has returned. js function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 2. Explain event delegation. Event delegation is a technique where you attach a single event listener to a parent element to handle events on its child elements using event.target. 3. What is the difference between == and ===? - `==` checks for value equality (type coercion allowed). - `===` checks for both value and type (strict equality). js '5' == 5 // true '5' === 5 // false 4. What is the "this" keyword? this refers to the object that is executing the current function. In arrow functions, this is lexically bound (based on where it's defined). 5. What are Promises? Promises handle asynchronous operations. They have 3 states: pending, resolved, rejected. js const p = new Promise((resolve, reject) => { resolve("Success"); }); p.then(console.log); 6. Explain async/await. Syntactic sugar over Promises for better readability in async code. js async function fetchData() { const res = await fetch(url); const data = await res.json(); } 7. What is hoisting? Variables and function declarations are moved to the top of their scope before code execution. js console.log(a); // undefined var a = 5; 8. What are arrow functions and how do they differ? Arrow functions are shorter and do not have their own this, arguments, or super. js const add = (a, b) => a + b; 9. What is the event loop? The event loop handles asynchronous callbacks and ensures non-blocking behavior in JS by placing them in the task queue after the call stack is clear. 10. What are IIFEs (Immediately Invoked Function Expressions)? Functions that run as soon as they are defined. js (function() { console.log("Runs immediately"); })();
To view or add a comment, sign in
-
Learn these JavaScript topics to crack your next Frontend Interview -> 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀: variables, data types, operators. -> 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀: scope, closures, and the this keyword. -> 𝗘𝗦6 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀: arrow functions, destructuring, spread/rest, template literals. -> 𝗔𝘀𝘆𝗻𝗰 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: promises and async/await. -> 𝗗𝗢𝗠 𝗠𝗮𝗻𝗶𝗽𝘂𝗹𝗮𝘁𝗶𝗼𝗻: working effectively with the Document Object Model. -> 𝗘𝘃𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: listeners, delegation, event object. -> 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀 & 𝗖𝗹𝗮𝘀𝘀𝗲𝘀: prototypal inheritance and ES6 classes. -> 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀: an essential and frequently tested concept. -> 𝗠𝗼𝗱𝘂𝗹𝗲 𝗦𝘆𝘀𝘁𝗲𝗺𝘀: CommonJS, AMD, ES6 modules. -> 𝗔𝗝𝗔𝗫 & 𝗙𝗲𝘁𝗰𝗵 𝗔𝗣𝗜: making asynchronous HTTP requests. -> 𝗗𝗲𝘀𝗶𝗴𝗻 𝗣𝗮𝘁𝘁𝗲𝗿𝗻𝘀: Singleton, Observer, Module. -> 𝗝𝗦𝗢𝗡: parsing and stringifying data. -> 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: using try…catch effectively. -> 𝗗𝗮𝘁𝗮 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀: arrays, objects, maps, sets. -> 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴: map, filter, reduce. -> 𝗕𝘂𝗶𝗹𝗱 𝗧𝗼𝗼𝗹𝘀: Webpack, Babel. -> 𝗧𝗲𝘀𝘁𝗶𝗻𝗴: Jest, Mocha, or similar frameworks. -> 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴: mastering browser developer tools. -> 𝗖𝗼𝗱𝗲 𝗤𝘂𝗮𝗹𝗶𝘁𝘆: ESLint and clean coding practices. -> 𝗦𝗲𝗰𝘂𝗿𝗶𝘁𝘆: XSS, CSRF, and other common vulnerabilities. -> 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 & 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁: handling async code with confidence. -> 𝗠𝗼𝗱𝗲𝗿𝗻 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸𝘀: React, Angular, or Vue. -> 𝗔𝗣𝗜𝘀: integrating external APIs. -> 𝗗𝗼𝗰𝘂𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻: writing clear and maintainable docs. -> 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻: task runners like Gulp, Grunt. -> 𝗣𝗪𝗔𝘀: service workers and offline-first concepts. -> 𝗪𝗲𝗯 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲: writing optimized, efficient code. If you’re preparing for frontend interviews, JavaScript is non-negotiable. 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗚𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲: https://lnkd.in/dauSXK5R Don’t forget to Repost this for your network! #javascript #frontend #interview #career #mern
To view or add a comment, sign in
-
The first time I truly nailed the callback question in a JavaScript interview 👇 1️⃣ Interviewer: What is a callback function in JavaScript? Me: A callback is a function that can be passed as an argument to another function, and it’s invoked later by that main function. 2️⃣ Interviewer: Okay, but assume I don’t know callbacks at all. Help me understand the idea. Me: Sure! Let me explain literally — why the function is called a “callback.” Let’s say we have a function like this 👇 function main(callback) { console.log("I finish my job"); callback(); } main(function() { console.log("Where are you?"); }); Output: I finish my job Where are you? Here, the main function finishes its own job first and then calls back another function. That’s why it’s named callback function. 3️⃣ Interviewer: Sounds good. Can you tell me why callback functions are needed in real-world JavaScript? Me: Well, Let’s first talk about Synchronous and Asynchronous behavior in JavaScript. Callbacks were born to handle asynchronous situations - when one task takes time - API call, timeout; and you don’t want to block the rest of your code. Example - setTimeout(() => { console.log("timeout"); }, 2000); Here, the () => { console.log("timeout") } part is a callback. Now, setTimeout is sent to the Web API. After 2 seconds, the callback is queued and then executed when the JavaScript engine is ready. 4️⃣ Interviewer: So, what I understand is - a callback always stays in the queue until the executing function finishes its job. Me: Not always, they’re used in synchronous ones too. In the first main() example, the callback was executed instantly once the main function completed. 5️⃣ Interviewer: Oh yes! I’ve seen callbacks in jQuery click events - they trigger instantly. Me: Exactly! But even that’s technically asynchronous, because the callback triggers when the browser detects the click event, which just happens very fast. 🗣️ Interviewer: That’s exactly how I wanted callbacks to be explained. Me: My pleasure — happy to help you understand the idea. #javascript #frontend #webdevelopment #interviewexperience #callback #learnjavascript #codingjourney #developerlife #programming #techcommunity
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development