💡JavaScript Array Methods — Simplified! 🧩 1️⃣ map() Definition: Creates a new array by applying a function to each element of the original array. const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] 🧩 2️⃣ filter() Definition: Creates a new array with elements that pass the given test condition. const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); console.log(even); // [2, 4] 🧩 3️⃣ find() Definition: Returns the first element that satisfies the given condition. const nums = [5, 10, 15]; const found = nums.find(n => n > 8); console.log(found); // 10 🧩 4️⃣ findIndex() Definition: Returns the index of the first element that satisfies the condition. const nums = [3, 6, 9]; const index = nums.findIndex(n => n === 6); console.log(index); // 1 🧩 5️⃣ reduce() Definition: Executes a reducer function on each element, resulting in a single output value. const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10 🧩 6️⃣ join() Definition: Joins all elements of an array into a string. const words = ['JavaScript', 'is', 'awesome']; console.log(words.join(' ')); // "JavaScript is awesome" 🧩 7️⃣ split() Definition: Splits a string into an array based on a separator. const sentence = "Hello World"; console.log(sentence.split(' ')); // ['Hello', 'World'] 💬Try combining these methods for powerful one-liners! const result = [1,2,3,4,5].filter(n=>n%2===0).map(n=>n*10); console.log(result); // [20, 40] 💡JavaScript Array Methods in Action! Ever wondered how to turn objects into readable strings, split them back, or calculate totals easily? Here’s a simple example combining map(), join(), split(), and reduce(): const users = [ { id: 1, name: "Emma", age: 22, price: 200 }, { id: 2, name: "Max", age: 32, price: 300 }, { id: 3, name: "Olivia", age: 27, price: 500 }, { id: 4, name: "John", age: 28, price: 300 } ]; // ❌ join() works on arrays of strings, not objects. // ✅ So first, map() to get only names: const nameString = users.map(user => user.name).join(", "); console.log(nameString); // Output: "Emma, Max, Olivia, John" // ✅ split() works on strings, not arrays of objects: const nameArray = nameString.split(", "); console.log(nameArray); // Output: ["Emma", "Max", "Olivia", "John"] // ✅ reduce() to calculate total price: const total = users.reduce((sum, user) => sum + user.price, 0); console.log(total); // Output: 1300 🧠 What’s happening here? map() → Extracts only the names join() → Combines them into a single string split() → Converts the string back into an array reduce() → Sums up all prices #JavaScript #WebDevelopment #Coding Ajay Suneja 🇮🇳 ( Technical Suneja )
"Mastering JavaScript Array Methods for Web Development"
More Relevant Posts
-
💭 What do you think — will this effect run on every click? const Counter = () => { const [count, setCount] = React.useState(0); const config = { theme: "dark" }; React.useEffect(() => { console.log("Effect ran"); }, [config]); return <button onClick={() => setCount(count + 1)}>Click</button>; }; At first glance, config looks static. But… this effect will run on every single click 🧨 Let’s break down why — from JavaScript memory to React Fiber internals 👇 🧠 1. JS Basics — Reference Types In JavaScript, objects & functions are reference types — compared by memory address, not content. { a: 1 } === { a: 1 } // false () => {} === () => {} // false Every render recreates: const config = { theme: "dark" } → a new object in memory → a new reference. ⚛️ 2. Under the Hood — React Fiber When setCount triggers a re-render: React creates a new Fiber node for the current render. The previous Fiber is kept as the alternate. React compares them during reconciliation. 🔄 3. Effect Dependency Comparison React checks dependencies via: Object.is(prevDep, nextDep) Since each render creates a new config reference, the comparison fails → effect runs again. 🧩 Render 1 → config ref#1 Render 2 → config ref#2 → Object.is(ref#1, ref#2) → false → Effect runs ⚡️ 🧘♂️ 4. The Fix To prevent unnecessary re-runs, stabilize the reference: const config = React.useMemo(() => ({ theme: "dark" }), []); Or, if it’s static, define it outside the component: const config = { theme: "dark" }; ✅ Summary Each render → new Fiber node New objects/functions → new references React compares deps via Object.is(prev, next) Different refs = effect re-runs Use useMemo / useCallback to stabilize references 🔍 Takeaway: Every render isn’t just new JSX — it’s new memory, new references, and a new Fiber snapshot. Understanding that is what separates debugging React from mastering it. 🚀
To view or add a comment, sign in
-
In JavaScript, let arr = [] is not an array! This looks like an array, but it's not. At least, not in the way a C++ or Rust developer would define one. This distinction is crucial for understanding JS performance. 🖥️ The "Real" Array (Low-Level) In low-level languages, an array is a fixed-size, contiguous block of memory. If you declare [i32; 4] in Rust, you allocate exactly 128 bits (4 * 32-bit integers). - Pro: Extremely fast and memory-predictable. - Con: It's rigid. You can't just .append(). There's no guarantee the memory slot "next door" is free. 🧙♂️ The JavaScript "Array" (High-Level) A JS Array is actually a highly optimized, dynamic Object in disguise. The engine (like V8) is smart. It runs "optimizations" based on how you use the array. It generally picks between two internal structures: 1. The "Fast" Mode (Dynamic Array) - When: You use it sequentially (e.t., .push(), .pop()). - How: The engine allocates a contiguous block of memory with extra capacity (just like a Rust Vec or C++ std::vector). - The Catch: When that capacity runs out, the engine must allocate a new, larger block and copy all the old elements over. - This is why push() is usually O(1) (amortized), but sometimes O(n). 2. The "Slow" Mode (Hash Map) - When: You create a sparse array (e.g., arr[0] = 1; arr[1000] = 2;). - How: The engine sees this and gives up on the contiguous block. It's a waste of memory. - It switches the array's internal structure to a hash map (or dictionary). It only stores the key-value pairs that actually exist ('0': 1, '1000': 2). The Takeaway JavaScript trades the raw memory predictability of a C/Rust array for incredible developer flexibility. It's not a simple memory block; it's a sophisticated data structure managed by the engine, constantly adapting to your code. Knowing when it might be a fast array vs. a slow hash map is key to writing high-performance JS. #JavaScript #V8 #NodeJs #SoftwareArchitecture #Performance #DataStructures #JSEngine #TypeScript
To view or add a comment, sign in
-
Today I revised some of the most essential JavaScript concepts that appear in real-world development. 1️⃣ Higher-Order Function (HOF) ✅ Question: Create a function that runs another function twice 📝 Code: function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("hello")); 🔍 Short Explanation: A HOF is a function that takes another function as input or returns a function. Helps in reusable logic. 2️⃣ Pure Function 📝 Code: function pure(a, b) { console.log(a + b); } pure(2, 3); pure(2, 3); 🔍 Short Explanation: Always gives the same output for the same input. No side effects. 3️⃣ Impure Function 📝 Code: let global = 0; function imPure(a) { global++; console.log(a + global); } imPure(2); imPure(2); 🔍 Short Explanation: Depends on external data → output changes unexpectedly. 4️⃣ Destructuring in Function Parameters 📝 Code: const obj = { name: "Pratik", age: 21 }; function destructuring({ name, age }) { console.log(name, age); } destructuring(obj); 🔍 Short Explanation: Pulls values directly from objects → cleaner code. 5️⃣ Normal Function vs Arrow Function (this difference) 📝 Code: let objTwo = { name: "Pratik", fnc: function () { console.log(this); }, arrowFnc: () => { console.log(this); } }; objTwo.fnc(); objTwo.arrowFnc(); 🔍 Short Explanation: Normal function → owns its own this Arrow function → uses parent this (lexical) 6️⃣ map(): Square each number 📝 Code: let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(e => e * e); console.log(newArr); 🔍 Short Explanation: Transforms each element → returns a new array. 7️⃣ filter(): Get even numbers 📝 Code: let filtered = arr.filter(e => e % 2 === 0); console.log(filtered); 🔍 Short Explanation: Keeps only the elements that match a condition. 8️⃣ reduce(): Total salary 📝 Code: let salary = [10000, 20000, 30000]; let total = salary.reduce((acc, v) => acc + v, 0); console.log(total); 🔍 Short Explanation: Reduces an array into one final value. 9️⃣ some() & every() 📝 Code: let names = ["pratik", "sun", "om", "krish", "vijay"]; let some = names.some(e => e.length > 3); let every = names.every(e => e.length > 3); console.log(some, every); 🔍 Short Explanation: some() → at least ONE matches every() → ALL must match 🔟 Object.freeze() 📝 Code: const users = { name: "Sunny", age: 21 }; Object.freeze(users); users.age = 22; users.city = "Surat"; delete users.name; console.log(users); 🔍 Short Explanation: No add, no delete, no modify → completely locked. 1️⃣1️⃣ Object.seal() 📝 Code: const test = { subject: "Maths", score: 50 }; Object.seal(test); test.score = 60; test.grade = "A"; delete test.subject; console.log(test); 🔍 Short Explanation: You can modify, but cannot add or delete keys. 1️⃣2️⃣ Optional Chaining (?.) 📝 Code: const user = { name: "Pratik", address: { city: "Surat" } }; console.log(user?.address?.city); 🔍 Short Explanation: Avoids errors when accessing nested properties.
To view or add a comment, sign in
-
If you call yourself a JavaScript developer,then these are the concepts you must be aware of Knowing just the basics won't cut it anymore. Here’s a roadmap of concepts I believe every developer should master: 1. Array Buffer & Typed Arrays 2. Array Destructuring 3. Array Methods (map, filter & more) 4. Arrow Functions Vs. Regular Functions 5. Async / Await 6. Bitwise Operators 7. call(), apply(), bind() 8. Callbacks 9. Canvas API 10. Clean Code Practices in JavaScript 11. Client-Side Routing 12. Closures 13. Code Splitting 14. Cross-Browser Compatibility 15. Cross-Origin Resource Sharing (CORS) 16. Currying 17. Custom Events 18. Debounce vs Throttle 19. Debouncing and Throttling 20. Deep vs. Shallow Copy 21. Design Patterns (Observer, Singleton, Factory, etc.) 22. Destructuring 23. Destructuring Assignment 24. Destructuring Nested Objects/Arrays 25. DOM Manipulation 26. Dynamic Imports 27. Dynamic Typing 28. Equality Operators (== vs ===) 29. Error Boundaries (in React.js) 30. Error Handling (Try/Catch/Throw) 31. ES6 Features (Arrow Functions, Classes, Modules, Destructuring) 32. Event Bubbling and Capturing 33. Event Delegation 34. Event Handling (addEventListener) 35. Event Loop 36. Fetch API 37. Functions 38. Generator Functions 39. Geolocation API 40. Geolocation vs Location Services 41. Global and Local Object (window, globalThis) 42. Hoisting 43. IIFE (Immediately Invoked Function Expression) 44. Inheritance (Class-based) 45. Intersection Observer API 46. JavaScript Memory Management (Garbage Collection) 47. JavaScript vs ECMAScript 48. JSON 49. Lazy Loading 50. Map and Set 51. Memoization 52. Methods 53. Module Pattern 54. Modules (Import/Export) 55. MutationObserver 56. NaN (Not a Number) 57. Object 58. Object Literal Shorthand 59. Object.assign() 60. Performance Optimization 61. Polyfills 62. Promise.all() 63. Promises 64. Prototypal Inheritance 65. RegEx (Regular Expressions) 66. Scope (Function vs Block Scope) 67. Service Workers 68. Set and Map Iteration 69. Set vs Map 70. SetTimeout and SetInterval 71. Shadow DOM 72. Template Literals 73. Shadowing 74. Spread & Rest Operators 75. Strict Mode 76. SVG Manipulation 77. Web Workers & WebSockets 78. This Keyword 79. Boolean Values 80. let, var & const 81. Type Coercion vs Type Conversion 82. URL API (URLSearchParams, URL objects) 83. WeakMap & WeakSet 84. Web Animations 85. localStorage & sessionStorage Built for you: For DSA Prep: ✅ Notes that are concise and clear ✅ Most-asked questions per topic ✅ Real patterns + approaches 👉 Grab the DSA Guide → https://lnkd.in/d8fbNtNv For ReactJS Prep: ✅ Handwritten notes ✅ Interview-focused ✅ Covers fundamentals 👉 Grab the React Guide → https://lnkd.in/dpDy_i2W 𝐅𝐨𝐫 𝐌𝐨𝐫𝐞 𝐃𝐞𝐯 𝐈𝐧𝐬𝐢𝐠𝐡𝐭𝐬 𝐉𝐨𝐢𝐧 𝐌𝐲 𝐂𝐨𝐦𝐦𝐮𝐧𝐢𝐭𝐲: Telegram → https://lnkd.in/d_PjD86B Whatsapp → https://lnkd.in/dvk8prj5 Built for devs who want to crack interviews
To view or add a comment, sign in
-
💡 JavaScript Series | Topic 3 | Part 2 — Understanding Closures: Functions with Memory 👇 Closures are like functions with built-in memory 🧠. They remember variables from their surrounding scope, even after that scope is gone. This “memory” makes closures one of JavaScript’s most powerful features — enabling encapsulation, data privacy, and persistent state. 🧩 Here’s How a Closure is Formed function createGreeting(name) { let greeting = "Hello, " + name; // This inner function forms a closure, capturing 'greeting' return function() { console.log(greeting); }; } // Let's create two different greetings const greetJohn = createGreeting("John"); const greetJane = createGreeting("Jane"); // Each function "remembers" its own 'greeting' greetJohn(); // "Hello, John" greetJane(); // "Hello, Jane" ⚙️ What’s Happening Here 1️⃣ When createGreeting("John") is called — a new scope is created containing greeting = "Hello, John" 2️⃣ The inner function (returned one) keeps a reference to that scope. 3️⃣ Even after createGreeting finishes executing, the closure preserves the variable through that reference. That’s why each greetJohn() and greetJane() call prints their unique greeting — they remember the environment where they were created. ❤️ 🔐 Closures in Real-World Scenarios Closures are everywhere in production code 👇 ✅ Private Data: Encapsulate logic inside functions without exposing internals ✅ Event Handlers: Maintain state across callbacks ✅ Factories / Counters: Generate reusable stateful functions Example — Private Counter using Closure: function counter() { let count = 0; // private variable return { increment: () => ++count, decrement: () => --count, getValue: () => count }; } const c = counter(); console.log(c.increment()); // 1 console.log(c.increment()); // 2 console.log(c.getValue()); // 2 ✅ count isn’t directly accessible — yet it persists inside the closure. 💬 My Take: Closures are what make JavaScript beautifully powerful. They allow functions to “remember” — creating elegant solutions for private state, modular design, and async logic. Once you truly understand closures, you understand JavaScript’s soul. ❤️ 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #Closures #Scope #LexicalScope #WebDevelopment #Coding #ReactJS #NodeJS #NextJS #TypeScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
💡 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗥𝗲𝗮𝘀𝗼𝗻 𝗬𝗼𝘂𝗿 𝗖𝗼𝗱𝗲 𝗗𝗼𝗲𝘀𝗻’𝘁 𝗥𝘂𝗻 𝗶𝗻 𝗢𝗿𝗱𝗲𝗿⚙️ Most developers know about the Event Loop, but few truly understand how JavaScript executes your code step by step — from the Global Execution Context to Web APIs, Task Queues, and Microtasks 🌀 Let’s break it down like a system engineer 👇 🧠 𝗛𝗼𝘄 𝗶𝘁 𝗦𝘁𝗮𝗿𝘁𝘀 — 𝗧𝗵𝗲 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 When JavaScript runs, it first creates a Global Execution Context (GEC) — this contains: -> the Memory Component (variables, functions) -> the Code Component (thread of execution) It’s stored in the Call Stack, which works on a simple principle — LIFO (Last In, First Out). ⚙️ 𝗪𝗵𝗮𝘁 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 𝗪𝗵𝗲𝗻 𝗬𝗼𝘂 𝗖𝗮𝗹𝗹 𝗮 𝗧𝗶𝗺𝗲𝗿 𝗼𝗿 𝗔𝗣𝗜 The browser (or Node.js) provides Web APIs like: -> setTimeout -> fetch -> DOM events These are not part of JS itself — they are handled by the environment. Once completed, their callbacks move to the Task Queues. 🧩 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗧𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲𝘀 1️⃣ Macrotask Queue (Task Queue): Contains → setTimeout, setInterval, setImmediate, fetch callbacks, and DOM events. 2️⃣ Microtask Queue: Contains → Promise.then, async/await, and process.nextTick (Node.js). ⚡ 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗕𝗿𝗮𝗶𝗻 𝗼𝗳 𝗜𝘁 𝗔𝗹𝗹 After every macrotask, the Event Loop checks the Microtask Queue — and executes all microtasks before picking up the next macrotask. Why? Because microtasks are usually short, immediate reactions (like resolved Promises) and must run before the next rendering or I/O task. 🧩 𝗤𝘂𝗶𝗰𝗸 𝗗𝗲𝗺𝗼 console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); 📤 Output: Start End Microtask Macrotask ✅ The Microtask Queue (Promise) runs before Macrotask Queue (setTimeout). 💭 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: JavaScript is single-threaded, but not blocking — thanks to the event loop and task queues managing concurrency intelligently⚙️ Understanding this flow separates coders from engineers. #JavaScript #EventLoop #FrontendDevelopment #AsyncProgramming #WebDevelopment #FrontendEngineer #100DaysOfCode #SoftwareEngineering #TechLearning #Coding
To view or add a comment, sign in
-
-
🚀 WHY CONST AND LET AREN’T LIKE VAR IN JAVASCRIPT If you’ve ever wondered why const “isn’t hoisted”… Here’s the truth 👇 All variables in JavaScript are hoisted, but they’re initialized differently. 🧠 Memory Creation Phase (Before Code Runs) • Keyword Hoisting: Yes, with undefined. • Initialization: Yes. • Access Before Declaration: Allowed, resulting in ReferenceError for `let` and `const`, but undefined for `var`. ReferenceError💡 The time between scope entry and declaration is called the Temporal Dead Zone (TDZ) — the variable exists but can’t be accessed yet. console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(c); // ❌ ReferenceError var a = 10; let b = 20; const c = 30; ⚙️ What Happens Internally (Visualization) |------------------ JavaScript Execution Context ------------------| | Memory Phase (Hoisting) | var a → undefined | let b → <uninitialized> (TDZ) | const c → <uninitialized> (TDZ) |------------------------------------------------------------------| | Execution Phase | console.log(a) → undefined | console.log(b) → ReferenceError | console.log(c) → ReferenceError | a = 10; b = 20; c = 30; | console.log(a,b,c) → 10 20 30 |------------------------------------------------------------------| ✅ In short: "const and let are hoisted — but remain uninitialized until their declaration is executed." This behavior avoids unexpected bugs and makes JavaScript more predictable 💪 #JavaScript #WebDevelopment #Learning #Programming #CodeNewbie #Frontend
To view or add a comment, sign in
-
🔍 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴? Hoisting is JavaScript’s default behavior of 𝗺𝗼𝘃𝗶𝗻𝗴 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 (𝗻𝗼𝘁 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻𝘀) 𝘁𝗼 𝘁𝗵𝗲 𝘁𝗼𝗽 𝗼𝗳 𝘁𝗵𝗲𝗶𝗿 𝘀𝗰𝗼𝗽𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝗰𝗼𝗱𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻. In simpler terms — during the compilation phase, JavaScript "scans" your code and allocates memory for variables and function declarations before executing it. That’s why you can use certain functions or variables before they’re defined in your code! 📘 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 console.log(myVar); // Output: undefined var myVar = 10; Behind the scenes, JavaScript treats this like: var myVar; // Declaration hoisted console.log(myVar); // undefined myVar = 10; // Initialization happens here ➡️ var is hoisted and initialized with undefined. However, if you use let or const, they’re hoisted too — but not initialized, leading to a ReferenceError if accessed before declaration. console.log(myLet); // ❌ ReferenceError let myLet = 20; ⚙️ 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 sayHello(); // ✅ Works! function sayHello() { console.log("Hello, World!"); } ➡️ Function declarations are hoisted completely (both the name and definition). But function expressions are not fully hoisted: sayHi(); // ❌ TypeError: sayHi is not a function var sayHi = function() { console.log("Hi!"); }; 💡 𝗪𝗵𝘆 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 𝟭. 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁: Helps you reason about how JS interprets and runs your code. 𝟮. 𝗔𝘃𝗼𝗶𝗱 𝗕𝘂𝗴𝘀: Prevents confusion around “undefined” or “ReferenceError”. 𝟯. 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲: Hoisting is a frequent JS interview question — understanding it deeply gives you an edge. 🧠 𝗧𝗼𝗽 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 #𝟮 Q: What is Hoisting in JavaScript, and how does it affect variable and function declarations? A: Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. var is hoisted and initialized with undefined. let and const are hoisted but not initialized (Temporal Dead Zone). Function declarations are fully hoisted, while function expressions are not. 🎯 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. JavaScript hoists declarations, not initializations. 2. var behaves differently from let and const. 3. Function declarations can be used before they’re defined — but function expressions cannot. #JavaScript #Hoisting #WebDevelopment #InterviewPreparation #TechTips #JavaScriptInterviewQuestions
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 Ever wondered how JavaScript handles tasks without blocking the main thread? That’s where 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 come into play! ⚙️ 🧩 What is a Callback Function? 𝐀 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐢𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐧 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭 𝐭𝐨 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 — 𝐚𝐧𝐝 𝐢𝐬 𝐢𝐧𝐭𝐞𝐧𝐝𝐞𝐝 𝐭𝐨 𝐛𝐞 “𝐜𝐚𝐥𝐥𝐞𝐝 𝐛𝐚𝐜𝐤” 𝐥𝐚𝐭𝐞𝐫 𝐛𝐲 𝐭𝐡𝐚𝐭 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 💡 Since functions in JavaScript are First-Class Citizens, they can be treated like values — passed around, returned, or assigned to variables. 📖 Think of it like this: You give function 𝐗 the responsibility to call function𝐘 later. So,𝐘becomes the callback of𝐗. ----------------------------------------------------- ⏱️ Callbacks in Action: Handling Asynchronous Operations JavaScript is 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝, but callbacks allow it to perform non-blocking tasks like API calls, timers, or event handling. Here’s a simple example 👇 console.log("Start"); setTimeout(() => { console.log("⏰ This runs after 2 seconds"); }, 2000); console.log("End"); 🧠 Output: Start End ⏰ This runs after 2 seconds 💬 Explanation: When 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 is called, the callback goes into the Web API environment. The JS engine keeps running other code (non-blocking). After the timer expires, the callback moves to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞. It’s executed only when the Call Stack is empty, ensuring smooth asynchronous flow. 𝐓𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐚𝐠𝐢𝐜 𝐨𝐟 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 𝐞𝐧𝐚𝐛𝐥𝐢𝐧𝐠 𝐚𝐬𝐲𝐧𝐜 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐢𝐧 𝐚 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝 𝐰𝐨𝐫𝐥𝐝! ✨ -------------------------------------------------- 🔒 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 + 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 = 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐆𝐨𝐥𝐝 💬 Here’s a classic interview problem 👇 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: If you try to use a global counter variable, you risk having it modified by other parts of the code. A better solution is needed to keep the counter private and persistent. 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 (𝐂𝐥𝐨𝐬𝐮𝐫𝐞): By creating a function that wraps the counter and the event listener attachment, the event handler (the callback) forms a closure over the local variable (count). 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤() { 𝐥𝐞𝐭 𝐜𝐨𝐮𝐧𝐭 = 0; 𝐝𝐨𝐜𝐮𝐦𝐞𝐧𝐭.𝐠𝐞𝐭𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐁𝐲𝐈𝐝("𝐛𝐭𝐧").𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫("𝐜𝐥𝐢𝐜𝐤", 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧() { 𝐜𝐨𝐮𝐧𝐭++; 𝐜𝐨𝐧𝐬𝐨𝐥𝐞.𝐥𝐨𝐠("𝐁𝐮𝐭𝐭𝐨𝐧 𝐜𝐥𝐢𝐜𝐤𝐞𝐝", 𝐜𝐨𝐮𝐧𝐭, "𝐭𝐢𝐦𝐞𝐬"); }); } 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤(); 🧩 Explanation: The inner callback function forms a closure over the variable count. Even after handleClick() finishes executing, count stays alive in the callback’s Lexical Environment. This keeps the counter private, persistent, and secure — no memory Leaks. #JavaScript #WebDevelopment #LearningInPublic #NamasteJavaScript #FrontendDevelopment #CodingJourney
To view or add a comment, sign in
-
Let’s talk about a surprisingly underused but powerful tool in JavaScript: the Nullish Coalescing Operator (??). If you haven’t been using this gem yet, it might just simplify your code and help you avoid some common bugs related to default values. Here’s the problem it solves: often, you want to provide a fallback or default value when a variable is undefined or null. Previously, many of us leaned heavily on the logical OR (||) operator, like this: ```javascript const userInput = ''; const displayName = userInput || 'Guest'; // displayName will be 'Guest' ``` Looks fine, right? But wait—what if the user deliberately entered an empty string, which is a valid input here? The || operator treats empty strings, 0, NaN, and false as falsy and will override those with the fallback value. That can lead to unexpected behavior. Enter the Nullish Coalescing Operator (??): ```javascript const userInput = ''; const displayName = userInput ?? 'Guest'; // displayName will be '' ``` With ??, only null or undefined triggers the fallback. Empty strings, zeros, and false remain untouched. This is a cleaner, more precise way of handling defaults. This operator is especially useful in real-world cases such as: - Config settings, where 0 or false can be valid options. - API responses, where some fields can be omitted (undefined) but others deliberately falsey. - Form inputs, where user data might legitimately be falsey but not null. Here’s a quick snippet comparing the two approaches: ```javascript function getTimeout(config) { // Using OR operator const timeoutOld = config.timeout || 3000; // Using Nullish Coalescing const timeoutNew = config.timeout ?? 3000; console.log('Old:', timeoutOld, 'New:', timeoutNew); } getTimeout({ timeout: 0 }); // Output: // Old: 3000 New: 0 ``` See how ?? correctly respects 0 as a valid value, while || doesn’t? Pro tip: avoid mixing ?? with || in the same expression, as it can cause syntax errors or produce confusing results. Use parentheses if you must combine them. So if you want to write clearer, less bug-prone JavaScript, start using the Nullish Coalescing Operator. It might be a tiny change for your code but a giant leap in clarity and correctness. Have you used ?? in your projects yet? What scenarios made you appreciate it? Let’s swap tips in the comments! #JavaScript #WebDevelopment #CodingTips #TechTrends #Frontend #Programming #DeveloperExperience
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