Day 25: Currying in JavaScript 🍛 Currying sounds complicated… But it’s actually a powerful functional programming technique. 🔹 What is Currying? Currying is: Transforming a function that takes multiple arguments into a sequence of functions that take one argument at a time. Instead of this 👇 function add(a, b, c) { return a + b + c; } add(2, 3, 4); // 9 We do this 👇 function add(a) { return function (b) { return function (c) { return a + b + c; }; }; } add(2)(3)(4); // 9 One argument at a time 🔹 Why Use Currying? ✔ Improves reusability ✔ Helps create specialized functions ✔ Enables function composition ✔ Common in functional programming Real Practical Example function multiply(a) { return function (b) { return a * b; }; } const double = multiply(2); const triple = multiply(3); console.log(double(5)); // 10 console.log(triple(5)); // 15 Here: multiply(2) creates a reusable function That’s powerful abstraction 🔥Modern ES6 Version (Cleaner) const add = a => b => c => a + b + c; add(1)(2)(3); // 6 Short and elegant. 🔹 Currying vs Partial Application 👉 Currying → Always single argument functions 👉 Partial Application → Fix some arguments, not necessarily one by one Example of partial application: function add(a, b) { return a + b; } const add5 = add.bind(null, 5); console.log(add5(10)); // 15 🧠 Interview Insight Currying is possible in JavaScript because: ✔ Functions are first-class citizens ✔ Functions can return functions ✔ Closures preserve outer scope values 🔥 Where It’s Used? Redux Functional libraries like Lodash Middleware patterns Advanced React patterns #JavaScript #Currying #FunctionalProgramming #Frontend #WebDevelopment #LearnInPublic
Currying in JavaScript: Transforming Functions
More Relevant Posts
-
🚀 Higher-Order Functions in JavaScript — A Must-Know Concept! 💡 What is a Higher-Order Function? A function is called a Higher-Order Function if it: ✔️ Takes another function as an argument ✔️ Returns a function as its result 🔍 Simple Example: function greet(name) { return `Hello, ${name}`; } function processUserInput(callback) { const name = "Jake"; return callback(name); } console.log(processUserInput(greet)); 👉 Here, processUserInput is a Higher-Order Function because it accepts greet as a callback. ⚡ Why are Higher-Order Functions powerful? ✅ Code reusability ✅ Cleaner and more readable code ✅ Helps in functional programming ✅ Widely used in JavaScript methods like: array.map(), array.filter(), array.reduce() 🔥 Interview Twist: function multiplier(factor) { return function (number) { return number * factor; }; } const double = multiplier(2); console.log(double(5)); // ? 🧠 Output: 10 👉 Because multiplier returns another function — classic Higher-Order Function! 🔥 The Important Concept: Closure Even though multiplier execution is finished, the inner function still remembers factor. This is called a closure: "A function remembers variables from its outer scope even after that outer function has finished executing." #JavaScript #WebDevelopment #Frontend #CodingInterview #Developers
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop (Clearly & Practically) | Post 2 JavaScript is single-threaded — yet it handles asynchronous tasks like a pro. The secret behind this is the Event Loop 🔁 --- 📌 What is the Event Loop? The Event Loop is a mechanism that continuously checks: 👉 “Is the Call Stack empty?” If yes, it pushes pending tasks into execution. --- 🧩 Core Components 🔹 Call Stack Executes synchronous code line by line. 🔹 Web APIs (Browser / Node.js) Handles async operations like: - setTimeout - API calls - File operations 🔹 Callback Queue Stores callbacks once async tasks are completed. 🔹 Event Loop Moves callbacks from the queue to the Call Stack when it's free. --- 🔁 How It Works 1. Execute synchronous code 2. Send async tasks to Web APIs 3. Once done → push to Callback Queue 4. Event Loop checks → moves to Call Stack --- 🧠 Example console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); 👉 Output: Start → End → Async Task Even with "0ms", async tasks wait until the stack is empty. --- ⚡ Important Concept 👉 Microtasks vs Macrotasks ✔️ Microtasks (High Priority) - Promise.then - async/await ✔️ Macrotasks - setTimeout - setInterval 📌 Microtasks always execute before macrotasks. --- 🎯 Why You Should Care Understanding the Event Loop helps you: ✅ Write non-blocking, efficient code ✅ Debug async behavior easily ✅ Build scalable applications ✅ Crack JavaScript interviews --- 💬 Mastering this concept is a game-changer for every JavaScript developer. #JavaScript #EventLoop #WebDevelopment #NodeJS #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 5 / 100 — JavaScript Concepts That Every Developer Should Understand #100DaysOfCode Today I revised two very important JavaScript concepts that often come up in interviews and real-world debugging: 🔐 1. Closures A closure happens when a function remembers variables from its outer scope even after the outer function has finished executing. In simple words: A function carries its environment with it. Example: function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 Why this works: Even though outer() has finished running, inner() still remembers the variable count. 📌 Common use cases • Data privacy • Function factories • React hooks • Event handlers 🧠 2. Call Stack The call stack is how JavaScript keeps track of function execution. It works like a stack (Last In, First Out). Whenever a function runs: 1️⃣ It gets pushed onto the stack 2️⃣ When it finishes, it gets popped off Example: function one() { two(); } function two() { three(); } function three() { console.log("Hello from the call stack"); } one(); Execution order in the call stack: Call Stack three() two() one() global() Then it unwinds after execution. 📌 Understanding the call stack helps with: • Debugging errors • Understanding recursion • Avoiding stack overflow 💡 Key realization today: JavaScript is single-threaded, and concepts like closures + call stack explain a lot about how the language actually works behind the scenes. Mastering these fundamentals makes async JS, promises, and the event loop much easier later. 🔥 Day 5 completed. 95 days to go. If you're also learning to code, comment “100” and let’s stay consistent together 🤝 #javascript #100daysofcode #webdevelopment #coding #developers #programming #learninpublic #buildinpublic #SheryiansCodingSchool #Sheryians
To view or add a comment, sign in
-
-
🚀 JavaScript Developers: Understanding the Difference Between `map()`, `forEach()`, and `for` Loops When working with arrays in JavaScript, there are several ways to iterate over data. The most common ones are `map()`, `forEach()`, and the traditional `for` loop. Although they may look similar, they serve different purposes. --- 📌 for Loop The traditional `for` loop gives you full control over the iteration. • You define the start and end of the loop • You can use `break` or `continue` • Useful for complex logic or performance-sensitive operations Example: const numbers = [1, 2, 3, 4]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } --- 📌 forEach() `forEach()` is used when you want to execute an action for each element in an array. • Runs a function for every element • Does not return a new array • Commonly used for side effects like logging or triggering functions Example: const numbers = [1, 2, 3, 4]; numbers.forEach(num => { console.log(num); }); --- 📌 map() `map()` is used when you want to transform data and return a new array. • Applies a transformation to every element • Returns a new array Example: const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] --- 💡 Simple rule to remember • Use map() when you want a new transformed array • Use forEach() when you want to execute something for each item • Use for loops when you need more control over the loop Understanding these differences helps you write cleaner and more readable JavaScript code. 👨💻 Which one do you use the most in your projects? #JavaScript #WebDevelopment #Frontend #Programming #Developers #ReactJS
To view or add a comment, sign in
-
-
🚀 JavaScript Functions — Explained Functions are the backbone of JavaScript What is a Function? >> A function is a reusable block of code designed to perform a specific task. 1. Function Declaration: A function defined using the function keyword with a name. function greet(name) { return "Hello " + name; } ✔️ Hoisted (can be used before declaration) 2. Function Expression: A function stored inside a variable. const greet = function(name) { return "Hello " + name; }; ❌ Not hoisted like declarations 3. Arrow Function: A shorter syntax for writing functions using =>. const greet = (name) => "Hello " + name; ✔️ Clean and concise ⚠️ Does not have its own this 4. Parameters: Variables listed in the function definition. function add(a, b) { } >> a and b are parameters 5. Arguments: Actual values passed to a function when calling it. add(2, 3); >> 2 and 3 are arguments 6. Return Statement: The return keyword sends a value back from a function and stops execution. function add(a, b) { return a + b; } 7. Callback Function: A function passed as an argument to another function. function greet(name) { console.log("Hello " + name); } function processUser(callback) { callback("Javascript"); } 8. Higher-Order Function: A function that takes another function as an argument or returns a function. >> Examples: map(), filter(), reduce() 9. First-Class Functions: In JavaScript, functions are treated like variables. ✔️ Can be assigned to variables ✔️ Can be passed as arguments ✔️ Can be returned from other functions #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
🚀 Understanding "var" Scope in JavaScript In JavaScript, there are mainly three types of scope: 1️⃣ Global Scope – Variables declared outside any function are accessible everywhere in the program. 2️⃣ Function Scope – Variables declared inside a function can only be used inside that function. 3️⃣ Block Scope – Variables declared inside blocks like "{ }" (for example in "if", "for", etc.) are only accessible inside that block. However, the important thing to remember is: 👉 The "var" keyword only follows Global Scope and Function Scope. ❌ It does NOT follow Block Scope. Let’s look at a simple example: if (true) { var message = "Hello World"; } console.log(message); // Output: Hello World Even though "message" is declared inside the "if" block, we can still access it outside the block. This happens because "var" ignores block scope. Now look at a function example: function test() { var number = 10; console.log(number); // 10 } console.log(number); // Error: number is not defined Here, "number" is declared inside the function, so it cannot be accessed outside the function. ✅ Key Takeaway: - "var" → Global Scope + Function Scope - "var" ❌ does not support Block Scope That’s why modern JavaScript developers prefer "let" and "const", because they properly support block scope. #JavaScript #WebDevelopment #Programming #BackendDevelopment
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗼𝗳 𝗙𝘂𝗻𝗰𝗍𝗶𝗼𝗻.𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲.𝗯𝗶𝗻𝗱 Function.prototype.bind helps you manage context in JavaScript. It creates a new function with a specific this value and arguments. This is useful for event handlers, callbacks, and async programming. Here's how it works: - You call bind on a function, passing the this value and arguments. - The returned function is a new instance and can be called like a regular function. - The original function is not affected by the binding operation. You can use bind to set some parameters in advance, like currying. For example: ```javascript function multiply(a, b) { return a * b; } const double = multiply.bind(null, 2); console.log(double(5)); // 10 ``` Bind is also useful for preserving context in DOM manipulation and web applications. You can use it to throttle or debounce events. When using bind, be aware of performance implications, especially when re-binding functions on every render. It's also important to avoid memory leaks by using bind wisely. You can test context with mocks and use closures or arrow functions as alternatives to bind in certain situations. To learn more, check out: - MDN Web Docs: Function.prototype.bind - JavaScript: The Definitive Guide by David Flanagan - You Don’t Know JS (Book Series) by Kyle Simpson Source: https://lnkd.in/geZSC2qW
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop 🚀 Today I explored one of the most important concepts in JavaScript — the Event Loop. JavaScript is known as a single-threaded language, which means it can execute only one task at a time. But modern web applications perform many operations simultaneously, such as API calls, timers, and user interactions. This is where the Event Loop makes JavaScript powerful. 🔍 What’s Involved? The JavaScript runtime manages asynchronous operations using a few key components: • Call Stack – Executes synchronous code line by line • Web APIs – Handles asynchronous operations like setTimeout, DOM events, and API requests • Callback Queue – Stores callback functions waiting to be executed • Event Loop – Continuously checks if the call stack is empty and moves tasks from the queue to the stack Example: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even though the delay is 0, the callback runs later because it first goes to the callback queue, and the event loop executes it only when the call stack becomes empty. Why It Matters: ✅ Handles Asynchronous Operations Efficiently ✅ Improves Application Performance ✅ Prevents Blocking of the Main Thread ✅ Essential for APIs, Timers, and Event Handling ✅ Core concept for Node.js and modern web applications Understanding the Event Loop helps developers write better asynchronous code and debug complex JavaScript behavior. Currently exploring deeper JavaScript concepts step by step to strengthen my development skills. 💻 #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Developers #Programming #LearningJourney
To view or add a comment, sign in
-
🚀 5 Advanced JavaScript Concepts Every Developer Should Understand As you move beyond the basics in JavaScript, understanding some deeper concepts becomes very important. These concepts help you write better code, debug complex issues, and understand how JavaScript actually works behind the scenes. Here are 5 advanced JavaScript concepts every developer should know. 1️⃣ Closures Closures occur when a function remembers variables from its outer scope even after that outer function has finished executing. They are commonly used in callbacks, event handlers, and data privacy patterns. 2️⃣ The Event Loop JavaScript is single threaded, but it can still handle asynchronous operations through the Event Loop. Understanding the call stack, task queue, and microtask queue helps explain how asynchronous code runs. 3️⃣ Debouncing and Throttling These techniques control how often a function executes. They are extremely useful when handling events like scrolling, resizing, or search input to improve performance. 4️⃣ Prototypal Inheritance Unlike many other languages, JavaScript uses prototypes to enable inheritance. Understanding prototypes helps you understand how objects share properties and methods. 5️⃣ Currying Currying is a functional programming technique where a function takes multiple arguments one at a time. It allows you to create more reusable and flexible functions. Mastering concepts like these helps developers move from simply writing JavaScript to truly understanding how it works. Which JavaScript concept took you the longest to understand? #JavaScript #WebDevelopment #Programming #Developers #FrontendDeveloper
To view or add a comment, sign in
-
-
Understanding the JavaScript Event Loop is a game changer for writing efficient asynchronous code. Many developers use setTimeout and Promise daily — but fewer truly understand what happens behind the scenes. Here’s a quick breakdown 👇 🔹 JavaScript is single-threaded 🔹 Synchronous code runs first (Call Stack) 🔹 Then all Microtasks execute (Promises, queueMicrotask) 🔹 Then one Macrotask runs (setTimeout, setInterval, DOM events) 🔹 The loop repeats 📌 Execution Priority: Synchronous → Microtasks → Macrotasks Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); ✅ Output: 1 → 4 → 3 → 2 Understanding this helps in: ✔ Debugging async issues ✔ Optimizing performance ✔ Writing better React applications ✔ Cracking frontend interviews I’ve created a simple infographic to visually explain the entire Event Loop process. If you're preparing for JavaScript or React interviews, mastering this concept is essential. 💬 Now Your Turn 👇 What will be the output of this code? console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => { console.log("C"); }); console.log("D"); 👨💻 Follow for daily React, and JavaScript 👉 Arun Dubey Drop your answer in the comments 👇 Let’s see who really understands the Event Loop 🔥 #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #EventLoop #CodingInterview
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