Day 13/50 – JavaScript Interview Question? Question: What is hoisting in JavaScript? Simple Answer: Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase. Function declarations are fully hoisted, var declarations are hoisted but initialized as undefined, and let/const are hoisted but remain in the Temporal Dead Zone. 🧠 Why it matters in real projects: Understanding hoisting helps you avoid confusing bugs and write more predictable code. It explains why you can call functions before they're declared and why accessing var variables before declaration returns undefined instead of an error. 💡 One common mistake: Thinking hoisting physically moves code. It doesn't—it's about when variables and functions are registered in memory during the creation phase. 📌 Bonus: // Function hoisting - works! greet(); // "Hello" function greet() { console.log("Hello"); } // var hoisting - returns undefined console.log(name); // undefined (not ReferenceError) var name = "Alice"; // let/const - Temporal Dead Zone console.log(age); // ReferenceError let age = 25; // Function expressions are NOT fully hoisted sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log("Hi"); }; #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
Understanding JavaScript Hoisting and Its Impact on Code Predictability
More Relevant Posts
-
Day 20/50 – JavaScript Interview Question? Question: What is prototypal inheritance in JavaScript? Simple Answer: Prototypal inheritance is JavaScript's mechanism for objects to inherit properties and methods from other objects through the prototype chain. When you access a property, JavaScript first checks the object itself, then walks up the prototype chain until it finds the property or reaches null. 🧠 Why it matters in real projects: Understanding prototypes is fundamental to JavaScript's object model. It's how classes work under the hood, how built-in methods like Array.prototype.map() are available, and how you can extend native objects or create efficient object hierarchies. 💡 One common mistake: Confusing __proto__ (the actual link) with prototype (the property on constructor functions). Also, modifying built-in prototypes like Array.prototype in production code is considered a bad practice. 📌 Bonus: // Constructor function function Person(name) { this.name = name; } // Add method to prototype (shared by all instances) Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); alice.greet(); // "Hello, I'm Alice" // Prototype chain alice.hasOwnProperty('name'); // true (own property) alice.hasOwnProperty('greet'); // false (inherited) alice.__proto__ === Person.prototype; // true // Modern ES6 class syntax (same prototype underneath) class Employee extends Person { constructor(name, title) { super(name); this.title = title; } } const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherits from Person #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Prototypes #OOP
To view or add a comment, sign in
-
Javascript Interview Question ❓ 🧠 JavaScript Call Stack Explained (With Nested Functions) Ever wondered which function runs first when functions are nested in JavaScript? Let’s break it down 👇 function fn1() { function fn2() { function fn3() { console.log("fn3"); } fn3(); console.log("fn2"); } fn2(); console.log("fn1"); } fn1(); 🔍 What actually happens? JavaScript uses a Call Stack to execute functions. 📌 Rule: Call Stack follows LIFO (Last In, First Out) 🪜 Call Stack Flow (Visualized) Copy code fn3() ← executed & finished first fn2() fn1() ← called first, finished last ✔️ fn1 is called first ✔️ fn3 finishes first That’s LIFO in action 🔥 ❌ FIFO vs ✅ LIFO in JavaScript Call Stack ✅ LIFO Event Queue (setTimeout)✅ FIFO Microtask Queue (Promise)✅ FIFO 📌 Golden rule for interviews: Execution stack = LIFO Async queues = FIFO 🎯 Interview One-Liner JavaScript executes functions using a LIFO call stack, while asynchronous callbacks are processed via FIFO queues. If this cleared things up, drop a 👍 If you’ve ever been confused by this — you’re not alone 😄 Follow for JavaScript + Angular internals explained simply 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #CallStack #EventLoop #JSInterview #Angular #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 26/50 – JavaScript Interview Question? Question: What is currying in JavaScript? Simple Answer: Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of add(a, b), you get add(a)(b). 🧠 Why it matters in real projects: Currying enables partial application, function composition, and more reusable code. It's fundamental to functional programming libraries like Ramda and is used in Redux middleware, event handlers, and configuration functions. 💡 One common mistake: Over-currying simple functions where it adds complexity without benefit. Use currying when you need partial application or composition, not everywhere. 📌 Bonus: // Regular function function add(a, b, c) { return a + b + c; } add(1, 2, 3); // 6 // Curried version function curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; }; } curriedAdd(1)(2)(3); // 6 // Practical use: Partial application const add5 = curriedAdd(5); const add5and10 = add5(10); console.log(add5and10(3)); // 18 // Generic curry function function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; } // Usage const multiply = (a, b, c) => a * b * c; const curriedMultiply = curry(multiply); curriedMultiply(2)(3)(4); // 24 curriedMultiply(2, 3)(4); // 24 - flexible! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #FunctionalProgramming #Currying #WebDev #InterviewPrep
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 19 Topic: JavaScript Modules — ESM vs CommonJS Continuing my JavaScript interview preparation journey, today I revised an important modern JS topic: 👉 JavaScript Modules (ESM vs CommonJS) Modules help us organize code, reuse functions, and keep projects maintainable. But in interviews, one common question is: What is the difference between ES Modules and CommonJS? Let’s simplify it. 📚 Real-World Example: Library Borrowing 🟢 ES Modules (Modern Library) Imagine a modern self-service library. You can: Pick only the chapters you need Borrow specific books Load things on demand ✅ Lightweight ✅ Efficient ✅ Future standard This is how ESM imports work. 🟠 CommonJS (Traditional Library) In an old library: You ask for one recipe… But the librarian gives you the entire cookbook set 😅 ❌ Loads whole module ❌ Synchronous ✅ Still widely used in Node.js This is how require() works. 💻 ES Modules Example (Modern) math.js export const add = (a, b) => a + b; export const multiply = (a, b) => a * b; app.js import { add } from "./math.js"; console.log(add(2, 3)); ✅ Static ✅ Tree-shakable ✅ Works in browsers 💻 CommonJS Example (Node.js) math.js const add = (a, b) => a + b; module.exports = { add }; app.js const math = require("./math"); console.log(math.add(2, 3)); 🔥 Key Differences Feature ESM CommonJS Loading Static Runtime ✅ When to Use 👉 Use ESM for modern frontend and new Node projects 👉 Use CommonJS when working with legacy Node codebases 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Event Delegation deep dive, Memory leaks, and more. Let’s keep learning consistently 🚀 #JavaScript #InterviewPreparation #ESModules #CommonJS #NodeJS #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 17/50 – JavaScript Interview Question? Question: What is debouncing and how do you implement it? Simple Answer: Debouncing is a technique that delays function execution until a certain amount of time has passed since the last invocation. It's perfect for limiting how often a function runs in response to rapid events. 🧠 Why it matters in real projects: Debouncing is essential for optimizing search autocomplete, form validation, window resize handlers, and scroll events. Without it, you'd make hundreds of unnecessary API calls or trigger expensive calculations on every keystroke. 💡 One common mistake: Confusing debouncing with throttling. Debouncing waits for a pause in events, while throttling executes at regular intervals regardless of event frequency. 📌 Bonus: // Debounce implementation function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // Usage: Search autocomplete const searchAPI = (query) => { console.log('Searching for:', query); // Actual API call here }; const debouncedSearch = debounce(searchAPI, 500); // User types "javascript" // Only makes 1 API call after user stops typing for 500ms searchInput.addEventListener('input', (e) => { debouncedSearch(e.target.value); }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 3 Topic: JavaScript Event Loop Explained Simply Continuing my daily JavaScript interview brush-up, today I revised one of the most important interview topics: 👉 The JavaScript Event Loop This concept explains how JavaScript handles asynchronous tasks while still being single-threaded. Let’s break it down with a simple real-world example. 🍽 Real-World Example: Restaurant Kitchen Imagine a busy restaurant kitchen. 👨🍳 Chef = Call Stack The chef cooks one order at a time. 🧾 Order Board = Task Queue New orders are pinned and wait their turn. 🏃 Runner/Manager = Event Loop Checks if the chef is free and gives the next order. If cooking takes time, the chef doesn’t stand idle. Instead: Other quick tasks continue, Completed orders are delivered later. This keeps the kitchen efficient. JavaScript works the same way. 💻 JavaScript Example console.log("Start"); setTimeout(() => { console.log("Timer finished"); }, 2000); console.log("End"); Output: Start End Timer finished Why? 1️⃣ "Start" runs immediately. 2️⃣ Timer is sent to Web APIs. 3️⃣ "End" runs without waiting. 4️⃣ After 2 seconds, callback goes to queue. 5️⃣ Event Loop pushes it to stack when free. ✅ Why Event Loop Matters in Interviews Understanding it helps explain: • setTimeout behavior • Promises & async/await • Non-blocking JavaScript • UI responsiveness • Callback & microtask queues 📌 Goal: Revise JavaScript daily and share learnings while preparing for interviews. Next topics: Promises, Async/Await, Execution Context, Hoisting, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPrep #EventLoop #WebDevelopment #Frontend #LearningInPublic #Developers #CodingJourney #AsyncJavaScript
To view or add a comment, sign in
-
-
Day 15/50 – JavaScript Interview Question? Question: What is the Event Loop in JavaScript? Simple Answer: The Event Loop is the mechanism that handles asynchronous operations in JavaScript's single-threaded environment. It continuously checks the Call Stack and Task Queues, executing code in a specific order: synchronous code first, then microtasks (promises), then macrotasks (setTimeout, events). 🧠 Why it matters in real projects: Understanding the Event Loop is crucial for debugging asynchronous behavior, preventing UI blocking, and optimizing performance. It explains why promises execute before setTimeout even with 0ms delay. 💡 One common mistake: Not understanding the priority of microtasks vs macrotasks, leading to unexpected execution order in complex async code. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: Timeout'), 0); Promise.resolve() .then(() => console.log('3: Promise 1')) .then(() => console.log('4: Promise 2')); console.log('5: End'); // Output order: // 1: Start // 5: End // 3: Promise 1 // 4: Promise 2 // 2: Timeout // Why? Sync code → Microtasks (Promises) → Macrotasks (setTimeout) #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Recent javascript interview questions I was interviewed. Though i wasn't selected but it gave me clear picture of the missing gaps. When i retrospect : Idea here is not just understanding the concepts is enough, you need to practice them with examples to stay with them to demonstrate when asked. Most intervewiers start with asking its definition and then a followup to demonstrate with an example problem to be given to you. Also very importantly simulate to build logic under pressurized circumstances (This can be done by keeping consistency in writing atleast 1 or 2 programs everyday to solve from simple to medium complexity problems). You may start with already seeing the solution to program them to 'wet' yourself but over the time start thinking first to build a pseudocode and then gradually uplift to solve problems atleast partially before looking for answers. Key here is : Patience and the practice and I truly mean here after experiencing the rejection under the hot seat. 1.) Event loop test by predicting output below : console.log('1'); console.log('2'); setTimeout(() => { console.log("This message appears after 2 seconds."); }, 0) Promise.resolve(console.log('4')); console.log('5'); 2.) Implement to sort by ID and then by score : const users = [{ id: '3', name: 'Alex', score: '45'}, { id: '4', name: 'Steve', score: '10'}, { id: '1', name: 'John', score: '24'}, { id: '2', name: 'James', score: '45'}]; 3.) write a closure to increment/decrement count in javascript 4.) What is event propagation and delegation, stateless vs stateful Vs Pure components 5.) What are synthetic events , throttling and debouncing 6.) React lifecycle and what is producer and consumer in Context in react 7.) what is CORS 8.) CSS rendering and styling 9.) Different types of Promise with specifically allSettled.
To view or add a comment, sign in
-
Day 28/50 – JavaScript Interview Question? Question: What is destructuring in JavaScript? Simple Answer: Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. It provides a concise way to extract multiple values in a single statement. 🧠 Why it matters in real projects: Destructuring makes code cleaner and more readable, especially with React props, API responses, and function parameters. It's ubiquitous in modern JavaScript and reduces boilerplate code significantly. 💡 One common mistake: Trying to destructure null or undefined, which throws an error. Always provide default values or check for existence when destructuring data from APIs or external sources. 📌 Bonus: // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const user = { name: 'Alice', age: 30, city: 'NYC' }; const { name, age } = user; console.log(name); // "Alice" // Renaming variables const { name: userName, age: userAge } = user; // Default values (prevents undefined) const { country = 'USA' } = user; console.log(country); // "USA" // Nested destructuring const data = { user: { profile: { email: 'a@b.com' } } }; const { user: { profile: { email } } } = data; // React props destructuring function UserCard({ name, age, onDelete }) { return <div>{name}, {age}</div>; } // Function parameters function displayUser({ name, age = 18 }) { console.log(`${name} is ${age}`); } // Common mistake - destructuring undefined const { x } = null; // ✗ TypeError! const { x } = null || {}; // ✓ Safe with fallback #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ES6 #Destructuring #WebDev #InterviewPrep
To view or add a comment, sign in
-
🚀 Understanding Hoisting in JavaScript Hoisting is one of the most commonly asked topics in JavaScript interviews — and also one of the most misunderstood. In JavaScript, variable and function declarations are moved to the top of their scope during the creation phase of execution. This process is called hoisting. Example: console.log(a); // undefined var a = 10; Behind the scenes, JavaScript treats it like this: var a; console.log(a); // undefined a = 10; 🔹 Key Points: • var is hoisted and initialized with undefined • let and const are hoisted but stay in the Temporal Dead Zone • Function declarations are fully hoisted • Function expressions are not fully hoisted Example: sayHello(); // Works function sayHello() { console.log("Hello!"); } But: sayHi(); // Error const sayHi = function() { console.log("Hi!"); }; 💡 Tip: Hoisting happens during the execution context creation phase, before the code runs. Understanding hoisting makes debugging easier and strengthens your JavaScript fundamentals. #JavaScript #WebDevelopment #Frontend #Programming #React #InterviewPrep
To view or add a comment, sign in
Explore related topics
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