🚀 Day 24 – Functions & Advanced Concepts in JavaScript Today’s focus is not just theory — it’s how these concepts are used in REAL applications 👇 🔹 1. Debounce 👉 Executes function only after user stops triggering it for a delay. function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Real-time scenario: In an e-commerce website, when a user searches for a product, we don’t call API on every keystroke. Instead, we wait until the user stops typing → then trigger API. 👉 Prevents 20+ unnecessary API calls! 🔹 2. Throttle 👉 Ensures function runs only once in a given interval. function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; flag = false; fn.apply(this, args); setTimeout(() => { flag = true; }, limit); }; } Real-time scenario: While scrolling Instagram/LinkedIn feed, scroll events fire continuously. Throttle ensures smooth performance by limiting executions. 👉 Prevents UI lag & improves performance 🔹 3. Currying 👉 Converts multiple arguments into nested functions. function curry(a) { return function (b) { return function (c) { return a + b + c; }; }; } console.log(curry(2)(3)(4)); // 9 Real-time scenario: In large apps, we create reusable utility functions. Example: Tax calculator → instead of passing all values every time, we reuse partial functions. 👉 Helps in clean & reusable code 🔹 4. Memoization 👉 Caches results to avoid recalculating. function memoize(fn) { const cache = {}; return function (n) { if (cache[n]) return cache[n]; const result = fn(n); cache[n] = result; return result; }; } Real-time scenario: In dashboards (finance/analytics apps), heavy calculations run repeatedly. Memoization stores results → avoids recomputation. 🔹 5. Closures ⭐ 👉 A function remembers variables from its outer scope even after execution. function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Real-time scenario: ✔ Data hiding ✔ Maintaining state (like counters, caches) Used in: ✔ Counters (cart items count) ✔ Private variables (data hiding) ✔ setTimeout inside loops 👉 Helps maintain state without global variables 🔹 6. Pure Functions 👉 Function that always returns same output for same input and has no side effects. function add(a, b) { return a + b; } Real-time scenario: In state management (Angular/React), pure functions ensure predictable updates. Why important? ✔ Predictable ✔ Easy to test ✔ Used in frameworks like Angular & React 👉 Easier debugging & testing #JavaScript #FrontendDeveloper #Angular #InterviewPrep #Coding #WebDevelopment
JavaScript Functions & Concepts: Debounce, Throttle, Memoization & More
More Relevant Posts
-
Sorting is one of those interesting JavaScript concepts that many developers use every day, but fewer truly understand. Sorting an array of strings feels straightforward: const arr = ["banana", "apple", "aa", "fish", "cherry"]; console.log(arr.sort()); // ['aa', 'apple', 'banana', 'cherry', 'fish'] This works exactly as expected ✅ But things get interesting when we try the same with numbers: const arr = [100, 4, 3, 7, 0]; console.log(arr.sort()); // [0, 100, 3, 4, 7] At first glance, this looks wrong. So… why does this happen? 👀 The default behavior of sort() in JavaScript is lexicographic sorting, which means values are compared as strings, character by character, based on their Unicode values. So JavaScript internally treats this like: ["100", "4", "3", "7", "0"] Now it compares them as strings, not as numbers. For example: "0" comes first "100" comes before "3" because "1" < "3" That’s why the output becomes: [0, 100, 3, 4, 7] ✅ The solution: Comparator function, to sort numbers properly, we use a comparator: arr.sort((a, b) => a - b) This makes JavaScript compare the actual numeric values. It follows the three-way comparison rule: return < 0 → a comes before b return > 0 → b comes before a return 0 → keep original order Internally, the logic is similar to: if (result < 0) { // keep a before b } else if (result > 0) { // move b before a } else { // keep current order } So now numeric sorting works correctly: const arr = [100, 4, 3, 7, 0]; console.log(arr.sort((a, b) => a - b)); // [0, 3, 4, 7, 100] 🔽 Descending order For descending, just reverse the subtraction: const arr = [100, 4, 3, 7, 0]; console.log(arr.sort((a, b) => b - a)); // [100, 7, 4, 3, 0] This small concept taught me an important lesson: Don’t just memorize sort((a,b)=>a-b) Understand why it works. That deeper understanding makes debugging and interviews much easier. #JavaScript #WebDevelopment #Frontend #SDE #SoftwareEngineering #CodingJourney #JobSearch
To view or add a comment, sign in
-
Prototypes & the Prototype Chain If you’re using class in JavaScript, you’re already using prototypes whether you realize it or not. Today was about understanding what that actually means under the hood. What I focused on Prototypes & the chain Every object in JavaScript has an internal link to another object called its prototype. You don’t see it directly, but it’s always there. When you try to access a property, JavaScript follows a simple process: * First, it checks the object itself * If not found, it looks at the object’s prototype * If still not found, it keeps going up the chain * This continues until it either finds the property or reaches null That lookup flow is called the prototype chain. A simple example: ``` function Person(name) { this.name = name; } Person.prototype.sayHello = function () { return "Hello " + this.name; }; const user = new Person("Naim"); console.log(user.sayHello()); ``` Here’s what’s happening: * `user` does not have `sayHello` directly * JavaScript looks at `Person.prototype` * It finds `sayHello` there and executes it That’s the prototype chain in action. Manual inheritance (no class) Built inheritance from scratch using constructor functions to understand how objects can share behavior. ``` function Animal(name) { this.name = name; } Animal.prototype.speak = function () { return this.name + " makes a sound"; }; function Dog(name) { this.name = name; } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; const d = new Dog("Rex"); console.log(d.speak()); ``` What’s happening here: * `Dog` doesn’t have `speak` * Its prototype is linked to `Animal.prototype` * So JavaScript finds `speak` there through the chain This is the same mechanism behind class-based inheritance. Modifying prototypes A few behaviors stood out while testing: * Adding a method to a prototype affects all existing instances * Property lookup happens at runtime, not when the object is created * If an object defines its own property, it overrides the prototype (shadowing) Example: ``` Person.prototype.age = 25; console.log(user.age); // 25 user.age = 30; console.log(user.age); // 30 (shadows prototype) ``` Takeaway Prototypes are how JavaScript actually shares behavior between objects. The prototype chain is how JavaScript resolves properties. Once this clicks, things like inheritance, method sharing, and even some common bugs start making a lot more sense. #javascript #webdevelopment #frontend #learninginpublic
To view or add a comment, sign in
-
-
Day 4: Why doesn't JavaScript get confused? 🧩 Variable Environments & The Call Stack(How Functions works in JS) Today I explored how JavaScript handles multiple variables with the same name across different functions. Using the code below, I took a deep dive into the Variable Environment and the Call Stack. 💻 The Code Challenge: javascript var x = 1; a(); b(); console.log(x); function a() { var x = 10; console.log(x); } function b() { var x = 100; console.log(x); } 🧠 The "Behind the Scenes" Logic: 1️⃣ Global Execution Context (GEC): Memory Phase: x is set to undefined. Functions a and b are stored entirely. Execution Phase: x becomes 1. Then, a() is invoked. 2️⃣ The Function a() Context: A brand new Execution Context is created and pushed onto the Call Stack. This context has its own Variable Environment. The x inside here is local to a(). It logs 10, then the context is popped off the stack and destroyed. 3️⃣ The Function b() Context: Same process! A new context is pushed. Its local x is set to 100. It logs 100, then it's popped off the stack. 4️⃣ Back to Global: Finally, the last console.log(x) runs in the Global context. It looks at the GEC’s Variable Environment where x is still 1. 📚 Key Learnings: Variable Environment: Each execution context has its own "private room" for variables. The x in a() is completely different from the x in the Global scope. Call Stack: It acts as the "Manager," ensuring the browser knows exactly which execution context is currently running. Independence: Functions in JS are like mini-programs with their own memory space. This is the foundation for understanding Lexical Scope and Closures! Watching this happen live in the browser's "Sources" tab makes you realize that JS isn't "magic"—it's just very well-organized! 📂 #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingTips #FrontendEngineer #CodingLogic
To view or add a comment, sign in
-
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
Symbols were the way to create private fields in JavaScript before private fields were a standard language feature. And in some cases, they're still the best option out there for performance purposes. How do they work? Instead of creating a regular string like "my-key", you create a symbol like `Symbol("my-key")`. The value that `Symbol` returns is unique, meaning that `Symbol("my-key") !== Symbol("my-key")`. This means that a developer can't access your class field using `obj[Symbol("my-key")]`. Rather, only those who have a reference to the uniquely-created symbol can access the field. Consider this code: const key = Symbol("my-key"); obj[key] = "value"; // ... export { obj }; Here, we export `obj`, but not `key`, meaning only we have the ability to read and write the value (kind of). The `ws` Node.js package has been using this clever approach for a long time. Since private fields are a native feature in JS now, there usually isn't a reason to take this approach. However, you might still find it useful when making Custom Elements, or other kinds of classes that need to use event listeners (e.g., in Node). If you remember, I made a post wayyyyyy back explaining how static event listeners provide the best performance in JavaScript. Of course, static event listeners prevent you from accessing `this`. And if you need access to a private field in your event listener, you'll be forced to use `this#key` and lose the performance boost. This is where Symbols shine! Instead of accessing private data through `this#key`, you can access it through `instance[symbolKey]`! As long as you have access to the symbol in your class's file, you'll be able to access data that the rest of the outside world can't (kind of). If you've been catching my "kind of"s, there's a caveat here: JS gives developers a way to inspect all of an object's Symbols. Generally speaking, most developers don't know about the existence of the global function that allows this, and many don't even know about Symbols at all. Plus, Symbol-based properties don't show up in IDE IntelliSense as devs type. So Symbol-based fields are semi-private! Nonetheless, Symbol-based properties are not "perfectly private". You might still choose to use them for performance purposes. But the adventurous devs who love scrutinizing code to find and use the `_DO_NOT_USE` properties will still be able to have their way. As with all things, this is about trade-offs. In my Combobox component, I've mostly been using private fields. But I've reached for Symbols in cases where I really wanted to keep using static event handlers. ComboBoxedIn Logs #17 (No, I haven't forgotten about these.)
To view or add a comment, sign in
-
🚀 React Hooks: The Game-Changer Every Developer Must Master If you're working with React and still relying heavily on class components… it's time to level up. React Hooks completely transformed how we build components — making code cleaner, reusable, and easier to manage. Let’s break it down in a way that actually makes sense 👇 🔥 What are React Hooks? Hooks are special functions introduced in React 16.8 that allow you to use state and lifecycle features in functional components. 👉 No more bulky classes 👉 No more confusing this keyword 👉 Just clean, readable functions 🧠 Why Hooks Matter? ✔ Simplifies component logic ✔ Promotes code reuse ✔ Improves readability ✔ Makes testing easier ✔ Reduces boilerplate code ⚡ Most Important Hooks You Should Know 1. 🟢 useState Manages state inside functional components. JavaScript const [count, setCount] = useState(0); 👉 Perfect for counters, forms, toggles 2. 🔵 useEffect Handles side effects like API calls, subscriptions, DOM updates. JavaScript useEffect(() => { console.log("Component mounted"); }, []); 👉 Think of it as componentDidMount + componentDidUpdate + componentWillUnmount 3. 🟣 useContext Avoids prop drilling by sharing data globally. 👉 Great for themes, auth, user data 4. 🟡 useRef Access DOM elements or persist values without re-render. JavaScript const inputRef = useRef(); 5. 🔴 useMemo & useCallback Optimize performance by memoizing values and functions. 👉 Prevent unnecessary re-renders 👉 Crucial for large-scale apps 💡 Pro Tips (From Real Projects) ✅ Don’t overuse useEffect — keep dependencies clean ✅ Use useMemo only when performance actually matters ✅ Break complex logic into custom hooks ✅ Follow naming convention: useSomething() 🚀 Custom Hooks = Real Power You can create your own hooks to reuse logic: JavaScript function useFetch(url) { // reusable logic } 👉 This is where senior-level React starts 💯 ⚠️ Common Mistakes to Avoid ❌ Calling hooks inside loops/conditions ❌ Ignoring dependency array in useEffect ❌ Over-optimizing with memoization ❌ Mixing too much logic in one component 🏁 Final Thought React Hooks are not just a feature — they are a mindset shift. If you truly master hooks, you move from writing code ➝ to designing scalable front-end systems. 💬 Want React + .NET Interview Questions & Real Project Scenarios? Comment "HOOKS" and I’ll share 🚀 🔖 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #Coding #SoftwareDevelopment #TechLearning #Developers #100DaysOfCode #Programming #ReactDeveloper #AngularVsReact #DotNet #FullStackDeveloper
To view or add a comment, sign in
-
-
🚀 Today we are going to analyse the JavaScript microtask queue, macrotask queue, and event loop. A junior developer once asked me during a code review: "Why does Node.js behave differently even when the code looks simple?" So I gave him a small JavaScript snippet and asked him to predict the output. console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); He answered confidently: Start Timeout Promise End But when we ran the code, the output was: Start End Promise Timeout He looked confused. That’s when we started analysing how JavaScript actually works internally. 🧠 Step 1: JavaScript is Single Threaded JavaScript runs on a single thread. It executes code line by line inside the call stack. So first it runs: console.log("Start") → Start console.log("End") → End Now the stack becomes empty. ⚙️ Step 2: Macrotask Queue setTimeout goes to the macrotask queue. Even though timeout is 0ms, it does not execute immediately. It waits in the macrotask queue. Examples of macrotasks: • setTimeout • setInterval • setImmediate • I/O operations • HTTP requests ⚡ Step 3: Microtask Queue Promise goes to the microtask queue. Examples of microtasks: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick (Node.js) • queueMicrotask() Microtasks always get higher priority. They execute before macrotasks. 🔁 Step 4: Event Loop Now the event loop starts working. The event loop checks: Is the call stack empty? Yes Check microtask queue Execute all microtasks Then execute macrotasks So execution becomes: Start End Promise Timeout Now everything makes sense. 🏗️ Real Production Example Imagine a Node.js API: app.get("/users", async (req, res) => { console.log("Request received"); setTimeout(() => console.log("Logging"), 0); await Promise.resolve(); console.log("Processing"); res.send("Done"); }); Execution order: Request received Processing Logging Why? Because Promise (microtask) runs before setTimeout (macrotask). This directly affects: • API response time • Logging • Background jobs • Queue processing • Performance optimization 🎯 Why Every Node.js / NestJS / Next.js Developer Should Know This Because internally: • Async/Await uses Promises • API calls use Event Loop • Background jobs use Macrotasks • Middleware uses Microtasks • Performance depends on queue execution Without understanding this, debugging production issues becomes very difficult. 💡 Final Thought JavaScript is not just a language. It is an event-driven execution engine. If you understand microtask queue, macrotask queue, and event loop, you don’t just write code — you understand how the runtime thinks. And once you understand the runtime, you start building faster and more scalable systems. #JavaScript #NodeJS #EventLoop #Microtasks #Macrotasks #NextJS #NestJS #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
POST 1 — The JavaScript Event Loop Is Not What You Think ⚙️ Every JavaScript developer says they understand the event loop. Most of them don't. And that gap is exactly why async bugs are so hard to find and fix. Here's what's actually happening 👇 ───────────────────────── First — JavaScript is single-threaded. Always. One thread. One call stack. One thing running at a time. So how does it handle timers, fetch calls, and user events without freezing? It doesn't. The BROWSER does. And then it reports back. ───────────────────────── The pieces most developers mix up: The Call Stack → where your code actually runs. Functions get pushed in, executed, and popped out. This is the only place code runs. Web APIs → setTimeout, fetch, DOM events. These live OUTSIDE the JS engine — in the browser or Node runtime. They run in separate threads you never manage. The Task Queue (Macrotask Queue) → where callbacks from Web APIs wait to be picked up. setTimeout callbacks land here. The Microtask Queue → where Promise callbacks and queueMicrotask calls wait. This queue has HIGHER priority than the task queue. ───────────────────────── The loop itself: 1. Run everything currently on the call stack until it's empty 2. Drain the ENTIRE microtask queue — every single item, including new ones added during draining 3. Pick ONE task from the task queue 4. Go back to step 1 ───────────────────────── Why this produces bugs nobody expects: Promise.resolve().then() runs before setTimeout(() => {}, 0) — always. Microtasks can starve the task queue if you keep adding new ones during draining. Long synchronous code blocks EVERYTHING — no timers fire, no events respond, no UI updates. ───────────────────────── The practical rule: Never put heavy computation directly on the call stack. Break it up. Use setTimeout to yield back to the event loop. Keep microtask chains short and predictable. ───────────────────────── Did the microtask vs task queue distinction surprise you? Drop a comment below 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #WebPerformance
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗔 𝗛𝗲𝗮𝗱𝗹𝗶𝗻𝗲 Let's talk about making many similar items in JavaScript. You know how objects hold information in pairs? Like a name and a value. Example: let car = { color: "red", wheels: 4 }; Here, "color" and "wheels" are keys. "red" and 4 are values. If you need to make many cars, writing this over and over is a lot of work. That is where constructor functions help. What is a Constructor Function? A constructor function is a normal function you use to build objects. Good practice says these function names should start with a big letter. Example: function Car() { this.color = "red"; } In this code: "this" means the new object we are making. "this.color = 'red'" adds a "color" piece to that object. How to Make an Object with `new` You use the 'new' word to create an object. let myCar = new Car(); console.log(myCar); What happens when you use `new`? When you type `new Car()`: A fresh, blank object starts. "this" points to this new object. You add parts (properties) to the object. The object is given back to you. You do not need to write `return this`. Making Many Objects Each time you use `new`, a new, separate object appears. let car1 = new Car(); let car2 = new Car(); car1 and car2 are two different objects. Constructor Functions with Inputs You can let constructor functions take information when you use them. Example: function Car(color) { this.color = color; } let myCar = new Car("blue"); console.log(myCar); Now you can pick the color when you make the car. Adding More Parts and Actions You can add more properties and actions (methods) to your objects. Example: function Car(color, doors) { this.color = color; this.doors = doors; this.getDoors = function() { return this.doors; }; } let myCar = new Car("green", 4); console.log(myCar.getDoors()); Here: "color" and "doors" are properties. "getDoors()" is a method. You run methods with (). Things to Keep in Mind: - Start constructor function names with a capital letter. - Always use the `new` word to make objects. - `this` stands for the new object being built. - Each `new` makes a unique object. Source: https://lnkd.in/gGFAJSnH
To view or add a comment, sign in
-
Day 12 of 90: Migrating a Live AI App Frontend from HTML to React Today I rebuilt my AI chatbot frontend using React and Vite. The goal was not a visual redesign. The goal was a structural upgrade. Before: One index.html file handling the header, chat messages, input logic, styling and JavaScript. Everything in one place. After: Four focused components each with a single responsibility. App.jsx manages state and connects them. Component structure: Header.jsx — renders the app title and status indicator ChatWindow.jsx — renders the list of messages ChatBubble.jsx — renders one message with a copy button InputBox.jsx — manages the textarea and send button Three React concepts applied today: useState: Replaces manual DOM manipulation. Instead of using appendChild to add a new message div, I update the messages array using setMessages. React detects the change and re-renders automatically. The component always reflects the current state of the data. Props and lifting state up: The messages array and sendMessage function live in App.jsx because both ChatWindow and InputBox need access to them. App passes messages down to ChatWindow for display and sendMessage down to InputBox as onSend. Neither child manages data it does not own. Controlled inputs: The textarea value is controlled by React state. Every keystroke updates the input state via onChange. On submit, the value is sent to the API and the state resets to empty. Deployment change: Plain HTML deployment: Enable GitHub Pages in repository settings, point to the docs folder. React deployment: Install gh-pages, add homepage and deploy scripts to package.json, configure base path in vite.config.js, then run npm run deploy. The command builds the app, generates optimised static files and pushes them to the gh-pages branch automatically. 8 errors encountered today: 1. sendMessage not defined — passed as prop from App.jsx 2. Code pasted into wrong file — moved to correct component 3. Function name placed after parentheses — corrected syntax 4. class and onclick used instead of className and onClick — JSX attributes corrected 5. Container expanding on overflow instead of scrolling — fixed with #root CSS height constraint 6. Copy button not reflecting Copied state — added useState and setTimeout 7. Git ownership conflict on new project folder — resolved with safe.directory config 8. Branch named master instead of main — renamed before push The live app is visually identical to the original HTML version. That was the target. React migration done correctly is transparent to the user. The value is in the code architecture, not the interface. Day 13 tomorrow. #ReactJS #AIEngineering #BuildInPublic #100DaysOfCode #Nigeria #SoftwareEngineering #WebDevelopment
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