🚀 JavaScript Interview Prep Series — Day 30 Topic: Machine Coding (Building UI Components from Scratch) Today I revised a very important interview round used by many companies: 👉 Machine Coding Round In this round, you are asked to build a working feature or UI component from scratch within a limited time. Companies use this to test: • Problem solving • Code structure • UI logic • State management • Clean coding practices 🧱 Real-World Analogy: Building with LEGO Imagine building a house using LEGO blocks. 1️⃣ Blueprint (Requirements) Before building, you understand the requirements. Example task: Build a Todo App Requirements: Add task Delete task Mark task complete Update UI dynamically 2️⃣ Build Step-by-Step Like building a LEGO house piece by piece: 🧱 HTML → structure 🎨 CSS → styling ⚙️ JavaScript → logic Each part connects together to create a working component. 3️⃣ Final Working Component After assembling all parts: ✔ UI works ✔ Buttons trigger actions ✔ State updates correctly That’s the goal of machine coding. 💻 Example: Simple Todo App HTML <div id="todoApp"> <input id="todoInput" placeholder="Enter task"/> <button id="addBtn">Add</button> <ul id="todoList"></ul> </div> JavaScript Logic const input = document.getElementById("todoInput"); const addBtn = document.getElementById("addBtn"); const list = document.getElementById("todoList"); let todos = []; addBtn.addEventListener("click", () => { const text = input.value.trim(); if (!text) return; const todo = { id: Date.now(), text, done: false }; todos.push(todo); renderTodos(); input.value = ""; }); Render UI Javascript function renderTodos() { list.innerHTML = ""; todos.forEach(todo => { const li = document.createElement("li"); li.innerHTML = ` ${todo.text} <button onclick="deleteTodo(${todo.id})">X</button> `; list.appendChild(li); }); } function deleteTodo(id) { todos = todos.filter(todo => todo.id !== id); renderTodos(); } 🧠 Key Concepts Tested During machine coding interviews, companies evaluate: ✔ DOM Manipulation ✔ Event Handling ✔ State Management ✔ Clean Code Structure ✔ Edge Case Handling 🎯 Common Machine Coding Questions • Todo App • Star Rating Component • Infinite Scroll • Autocomplete Search • Modal / Popup Component • Image Carousel • Kanban Board ⚡ Pro Tips for Machine Coding ✅ Clarify requirements first ✅ Break problem into small parts ✅ Start with basic functionality ✅ Write modular functions ✅ Test edge cases 📌 30 days of JavaScript interview preparation completed. This journey helped me revise core concepts and practice explaining them clearly. Next focus: Advanced frontend architecture, performance optimization, and system design. Let’s keep building 🚀 #JavaScript #MachineCoding #FrontendInterview #WebDevelopment #CodingInterview #LearningInPublic #Developers #CodingJourney
Machine Coding Interview Prep: Building UI Components from Scratch
More Relevant Posts
-
here's some important JavaScript questions to crack interviews 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱? - Refers to the object that is currently executing the function - In global scope, this is the window object (in browsers) - Arrow functions do not have their own this 𝟮. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗮𝗹 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲? - JS objects inherit properties and methods from other objects via a prototype chain - Every object has a hidden __proto__ property pointing to its prototype - ES6 class syntax is just cleaner syntax over prototypal inheritance 𝟯. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝗽𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (...)? - Spread expands an array or object: const newArr = [...arr, 4, 5] - Rest collects remaining arguments into an array: function fn(a, ...rest) {} - Same syntax, different context position determines behavior - Great for copying arrays/objects without mutation 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴? - Extract values from arrays or objects into variables cleanly - Array: const [first, second] = [1, 2] - Object: const { name, age } = user - Supports default values: const { name = 'Guest' } = user 𝟱. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻? - Instead of adding listeners to each child element, add one listener to the parent - Uses event bubbling events travel up the DOM tree - More memory efficient for large lists or dynamic content - Check event.target inside the handler to identify which child was clicked 𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗰𝗮𝗹𝗹(), 𝗮𝗽𝗽𝗹𝘆()? - All three explicitly set the value of this - call() invokes immediately, passes args one by one - apply() invokes immediately, passes args as an array 𝟳. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻? - Caching the result of a function call so it doesn't recompute for the same input - Improves performance for expensive or repeated operations - Commonly implemented using closures and objects/Maps 𝟴. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗛𝗶𝗴𝗵𝗲𝗿-𝗢𝗿𝗱𝗲𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? - Functions that take other functions as arguments or return them - Examples: .map(), .filter(), .reduce(), .forEach() - Core concept in functional programming with JavaScript 𝟵. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗮𝗻𝗱 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆? - Shallow copy copies only the top level nested objects are still referenced - Object.assign() and spread {...obj} create shallow copies - Deep copy duplicates everything including nested levels 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗼𝗽𝘁𝗶𝗼𝗻𝗮𝗹 𝗰𝗵𝗮𝗶𝗻𝗶𝗻𝗴 (?.) 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹𝗶𝘀𝗵 𝗰𝗼𝗮𝗹𝗲𝘀𝗰𝗶𝗻𝗴 (??)? - ?. safely accesses nested properties without throwing if something is null/undefined - user?.address?.city returns undefined instead of crashing - ?? returns the right side only if the left is null or undefined Follow the Frontend Circle By Sakshi channel on WhatsApp: https://lnkd.in/gj5dp3fm 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝘂𝘀 𝗵𝗲𝗿𝗲 → https://lnkd.in/geqez4re
To view or add a comment, sign in
-
🚨 “You didn’t finish the coding question… yet you still move to the next Interview round.” Recently I went through a React + Full Stack interview process at a product-based company. Role: Senior UI Engineer Company : American Airlines Application: Got call from HR 3 Virtual Rounds 🧠 Round 1: DSA + Core JavaScript The first round tested problem-solving and JavaScript fundamentals. 🔴 DSA 1 coding problem (medium level) 👉 You’re implementing an on-screen keyboard layout. Given a list of strings representing the words a user might type, return only the words that could be typed using letters from a single row of a QWERTY keyboard. // Input: ["Hello", "Alaska", "Dad", "Peace"] // Output: ["Alaska", "Dad"] 🔴 JavaScript concepts Output-based questions on: Closures Objects Hoisting Prototypical inheritance Arrow functions vs normal functions 🔴 Some interesting questions: What is a memory leak? What are frontend optimization techniques? ❗️ Since I mentioned I worked with both React and Angular, the interviewer went deeper: Architectural difference between React vs Angular Result: Cleared -------------------------------------------------------------- ⚛️ Round 2: React + Full Stack This round focused on practical frontend engineering. Coding Task Build a Traffic Light component 🟢 Green – 15 sec 🔴 Red – 20 sec 🟡 Yellow – 10 sec After implementing it, the interviewer added a twist: ➡️ Add input fields to dynamically change the timing for each light. Time given: 30–35 minutes I implemented the traffic light logic but couldn’t complete the editable timing feature. Topics covered 👉What is FCP (First Contentful Paint)? 👉What is CORS? 👉Why does Postman not show CORS errors? 👉Network communication models: HTTP request Short Polling Long Polling SSE WS Result: Did not complete Traffic light but still moved to 3rd round ----------------------------------------------------------------------- 🏗️ Round 3: System Design + Engineering Practices This round was more senior-level thinking. 🔴 Topics included: 👉System Design 👉Design systems 👉SOLID principles 👉DevOps / Deployment 👉Different deployment strategies 👉CI/CD practices The interviewer went deep to check real hands-on experience with CI/CD and deployments. 👉 React architecture, How React handles Rendering? 🔴Coding task 👉Implement a custom React hook for API fetching with: Caching Custom response handling Reusable logic 📌 Final Result ❌ Wasn’t selected. 💡 Key Takeaway If you're preparing for product-based companies, don’t just focus on frameworks. Make sure you're comfortable with: Browser internals Networking models Performance optimization System design Deployment pipelines Because interviews often move from: React hooks → Browser internals → Networking → System design #frontend #reactjs #javascript #systemdesign #webdevelopment #interviewexperience #fullstackdeveloper #softwareengineering #techinterview #reactdeveloper
To view or add a comment, sign in
-
-
✅ *Top JavaScript Coding Interview Questions* 🧠💻 *1️⃣ What is the difference between `==` and `===` in JavaScript?* *Answer:* - `==` compares values with type coercion. - `===` compares both value *and* type (strict equality). ```js 5 == "5" // true 5 === "5" // false ``` *2️⃣ How to check if a variable is an array?* *Answer:* ```js Array.isArray(myVar); // returns true if myVar is an array ``` *3️⃣ What is a closure in JavaScript?* *Answer:* A closure is when an inner function has access to variables from an outer function even after the outer function has returned. ```js function outer() { let count = 0; return function inner() { return ++count; } } const counter = outer(); counter(); // 1 ``` *4️⃣ Explain event delegation.* *Answer:* Event delegation is a technique of handling events at a higher-level element rather than on individual elements by using event bubbling. ```js document.getElementById("parent").addEventListener("click", (e) => { if (e.target.tagName === "BUTTON") { console.log("Button clicked:", e.target.textContent); } }); ``` *5️⃣ What is the difference between `let`, `const`, and `var`?* *Answer:* - `var`: function-scoped, hoisted - `let`: block-scoped, reassignable - `const`: block-scoped, cannot be reassigned *6️⃣ How does `this` keyword behave?* *Answer:* - In global scope: `this` refers to the global object (e.g., `window` in browsers). - In object methods: `this` refers to the object. - In arrow functions: `this` is lexically bound (takes value from surrounding context). *7️⃣ Write a function to reverse a string.* ```js function reverseStr(str) { return str.split("").reverse().join(""); } reverseStr("hello"); // "olleh" ``` *8️⃣ What is the output?* ```js console.log(typeof null); // "object" ``` *Explanation:* This is a historical bug in JavaScript and remains for backward compatibility. 💬 *React ❤️ for more!*
To view or add a comment, sign in
-
🚀 JavaScript Interview Questions (Must Know in 2026) Preparing for frontend interviews? Here are top JavaScript questions with clear explanations + examples 👇 🔹 1. What is ECMAScript? ECMAScript (ES) is the standard/specification on which JavaScript is based (ES6, ES7…). 👉 JS = Implementation of ECMAScript 🔹 2. Difference: var vs let vs const var → function scoped, hoisted let → block scoped, re-assignable const → block scoped, NOT re-assignable let a = 10; a = 20; // ✅ const b = 10; b = 20; // ❌ Error 🔹 3. Spread vs Rest vs Default Params Spread → expands values Rest → collects values Default → fallback values const arr = [1,2]; const newArr = [...arr, 3]; // Spread function sum(...nums) { return nums.reduce((a,b)=>a+b); } // Rest function greet(name = "Guest") { return name; } // Default 🔹 4. Deep Copy vs Shallow Copy Shallow → copies reference Deep → copies actual values const obj = {a:1}; const copy = {...obj}; // shallow 🔹 5. Promise, Callback, Async/Await Callback → function passed Promise → handles async cleanly Async/Await → syntactic sugar async function getData() { const res = await fetch(url); return res.json(); } 🔹 6. Promise vs Callback 👉 Callback → messy (callback hell) 👉 Promise → chainable, readable 🔹 7. Event Bubbling vs Capturing Bubbling → child → parent Capturing → parent → child 🔹 8. Higher Order Function Function that takes/returns another function function greet(fn){ fn(); } 🔹 9. Types of Functions Function Declaration Function Expression 🔹 10. Arrow Function Short syntax + no own this const add = (a,b) => a+b; 🔹 11. call vs apply vs bind call → args separately apply → args as array bind → returns new function 🔹 12. Ways to Create an Object Object literal {} Constructor function Class Object.create() 💡 Pro Tip: Don’t just memorize — practice + explain in interviews 🔥 Want to crack frontend interviews faster? I help developers with mock interviews + guidance 👉 Book here: https://lnkd.in/dBmB5zdi� #javascript #frontend #webdevelopment #interviewpreparation #angular #react #coding #100DaysOfCode
To view or add a comment, sign in
-
-
JavaScript Interview Preparation — Most Asked Concepts When preparing for frontend interviews, strong JavaScript fundamentals are essential. Frameworks evolve rapidly, but the core concepts of JavaScript remain constant. Here are some common areas that interviewers focus on: 1. JavaScript Basics - Primitive vs Non-Primitive data types - typeof operator - null vs undefined - NaN behavior - Dynamic typing in JavaScript These questions assess your understanding of how JavaScript operates internally. 2. ES6 Features - Arrow functions - Template literals - Destructuring - Enhanced object literals - Promises ES6 introduced powerful and cleaner features that are prevalent in modern codebases. 3. Variables & Hoisting A frequently discussed topic. Understand: - var vs let vs const - Block scope vs function scope - Hoisting behavior - Temporal Dead Zone Many developers use these concepts daily but find it challenging to explain them during interviews. 4. Functions & Execution Context Key concepts include: - Arrow functions vs traditional functions - this keyword behavior - call(), apply(), bind() A grasp of execution context demonstrates a deep understanding of JavaScript runtime behavior. 5. Functional Programming Modern JavaScript relies on: - Higher-order functions - map() - filter() - reduce() These are commonly used in frontend codebases. 6. Scope & Closures One of the most crucial JavaScript topics. Understand: - Global scope - Local scope - Scope chain - Closures Closures frequently appear in frontend interview questions. 7. Browser Concepts Frontend developers should be familiar with: - DOM (Document Object Model) - BOM (Browser Object Model) - Event handling These concepts explain how JavaScript interacts with the browser. One truth about JavaScript interviews is that while frameworks change every few years, JavaScript fundamentals remain unchanged. A strong foundation makes learning frameworks like React, Angular, or Vue much easier. Save this for your next frontend interview
To view or add a comment, sign in
-
🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 (𝗢𝘂𝘁𝗽𝘂𝘁 𝗕𝗮𝘀𝗲𝗱) Many JavaScript interviews don’t test how much you know… They test how deeply you understand the language. Here are 3 small JavaScript snippets that often confuse developers in interviews 👇 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝘃𝗮𝗿 𝘃𝘀 𝗹𝗲𝘁 𝗶𝗻 𝗹𝗼𝗼𝗽𝘀 𝑓𝑜𝑟 (𝑣𝑎𝑟 𝑖 = 0; 𝑖 < 3; 𝑖++) { 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑖), 1000); } 𝗢𝘂𝘁𝗽𝘂𝘁: 3, 3, 3 💡 𝗪𝗵𝘆? var is 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘀𝗰𝗼𝗽𝗲𝗱, not block scoped. All callbacks share the same i variable. By the time setTimeout runs, the loop has finished and i = 3. ✔️ 𝗙𝗶𝘅 𝘂𝘀𝗶𝗻𝗴 𝗹𝗲𝘁 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Output: 0, 1 ,2 Because let creates a new binding for each iteration. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲 𝗖𝗼𝗲𝗿𝗰𝗶𝗼𝗻 console.log("5" - 3); console.log("5" + 3); console.log(true + true); Output: 2, 53, 2 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 JavaScript performs 𝗶𝗺𝗽𝗹𝗶𝗰𝗶𝘁 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻. "5" - 3 → number conversion → 5 - 3 = 2 "5" + 3 → string concatenation → "53" true + true → 1 + 1 = 2 👉 The + operator prefers string concatenation, while other operators trigger numeric conversion. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝘁𝗵𝗶𝘀 𝗶𝗻𝘀𝗶𝗱𝗲 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 const obj = { name: "Shubham", greet: function() { setTimeout(() => { console.log(this.name); }, 1000); } }; obj.greet(); Output: Shubham 💡 𝗪𝗵𝘆? Arrow functions do not have their own this. They inherit this from the surrounding scope. Here, this refers to obj. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗶𝗽 Most JavaScript interview questions revolve around: • Scope • Closures • this keyword • Type coercion • Event loop Mastering these concepts makes 𝗝𝗦 𝗶𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗺𝘂𝗰𝗵 𝗲𝗮𝘀𝗶𝗲𝗿. 🔥 𝗤𝘂𝗶𝗰𝗸 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 What will be the output of this? console.log([] + []); console.log([] + {}); console.log({} + []); Write your answers in the comments 👇 ♻️ If you found this helpful, repost to help other developers preparing for JavaScript interviews. 📌 Follow Shubham Kumar Raj for more such content😊 #javascript #webdevelopment #frontenddeveloper #codinginterview #softwaredevelopment #learnjavascript #100daysofcode #hiring
To view or add a comment, sign in
-
Day 47/50 – JavaScript Interview Question? Question: What is the difference between prototype and __proto__? Simple Answer: prototype is a property on constructor functions containing the object used as prototype for new instances. __proto__ is the actual internal link on every object pointing to its prototype. Use Object.getPrototypeOf() instead of __proto__. 🧠 Why it matters in real projects: Understanding the prototype chain explains how JavaScript inheritance works, how methods like .map() are available on arrays, and how classes work under the hood. Essential for creating efficient object hierarchies. 💡 One common mistake: Confusing prototype with __proto__, or modifying Object.prototype which affects all objects globally. Also using deprecated __proto__ instead of standard Object.getPrototypeOf(). 📌 Bonus: // Constructor function function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); // Key difference: console.log(Person.prototype); // Object with greet method console.log(alice.__proto__ === Person.prototype); // true console.log(Object.getPrototypeOf(alice) === Person.prototype); // true // Prototype chain: // alice → Person.prototype → Object.prototype → null // Inheritance example function Employee(name, title) { Person.call(this, name); this.title = title; } Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherited from Person // Modern ES6 equivalent class ModernEmployee extends Person { constructor(name, title) { super(name); this.title = title; } } // Best practices: // ✓ Use Object.getPrototypeOf() const proto = Object.getPrototypeOf(alice); // ✗ Don't modify Object.prototype Object.prototype.myMethod = function() {}; // BAD! // ✗ Don't use __proto__ directly (deprecated) // ✓ Use Object.setPrototypeOf() instead #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
https://lnkd.in/dbyywsDA Welcome to our JavaScript Objects Tutorial! 🚗👤 In this video, we'll dive deep into the world of JavaScript objects using relatable examples like cars and people. By the end of this tutorial, you'll have a solid understanding of how to create and use objects in JavaScript, making your coding journey smoother and more enjoyable! What You'll Learn: Introduction to JavaScript objects Creating objects with properties and methods Accessing and modifying object properties Practical examples with car and person objects Why Watch This Video? Whether you're a beginner or looking to brush up on your JavaScript skills, this tutorial is perfect for you. We'll break down complex concepts into easy-to-understand examples. 🚗👤 Example Code: javascript Copy code // Car object example let car = { make: 'Toyota', model: 'Corolla', year: 2020, start: function() { console.log('Car started'); } }; // Person object example let person = { name: 'John Doe', age: 30, greet: function() { console.log('Hello, ' + this.name); } }; Don't Forget to: 👍 Like this video if you found it helpful 💬 Leave a comment with your questions or suggestions 🔔 Subscribe for more JavaScript tutorials Timestamps: 0:00 Introduction 1:23 What are JavaScript Objects? 3:45 Car Object Example 🚗 7:30 Person Object Example 👤 10:15 Accessing Object Properties 12:50 Modifying Object Properties 15:00 Conclusion and Next Steps Stay tuned and happy coding! 🚗👤 Objects in JavaScript An object is a collection of related properties and/or methods. Properties are key-value pairs that describe an object, such as a person's first name, last name, age, etc. Methods are functions that belong to an object, such as a person saying hello or eating. Creating Objects You can create an object using the {} syntax, like this: const person = {}; You can add properties to an object using key-value pairs, separated by commas. For example: const Person = { Person.hair: 'Black', Person.eyes:"Two": 'Person.SkinColor:white;' }; You can access an object's properties using the dot notation, like this: person.firstName or person.age. Methods Methods are functions that belong to an object. You can add methods to an object using function expressions or arrow functions.
To view or add a comment, sign in
-
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming *Double Tap ❤️ For More*
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