Bug fixed — checkbox persistence in my React Todo app Problem: after checking a todo and reloading the page, the checkbox would appear unchecked. Root cause: the checked prop in the checkbox expects a boolean, but localStorage sometimes contained "true" / "false" (strings) or inconsistent shapes. That made the UI show wrong values after reload. Fix (two parts): Normalize stored data on init — use a lazy useState initializer to read from localStorage once and convert "true"/"false" strings to booleans safely. Update state immutably — toggle using map() and spread so the isCompleted flag is correctly flipped and persisted. Key snippets: // Initialize todos from localStorage (lazy initializer) const [todos, setTodos] = useState(() => { try { const raw = localStorage.getItem('todos'); if (!raw) return []; const parsed = JSON.parse(raw); return parsed.map(t => ({ id: t.id ?? uuidv4(), todo: typeof t.todo === 'string' ? t.todo : '', // normalize isCompleted: boolean or "true"/"false" isCompleted: typeof t.isCompleted === 'boolean' ? t.isCompleted : t.isCompleted === 'true', })); } catch { return []; } }); // Toggle handler (immutable update) const handleCheckbox = id => { setTodos(prev => prev.map(item => item.id === id ? { ...item, isCompleted: !item.isCompleted } : item )); }; // Persist whenever todos change useEffect(() => { localStorage.setItem('todos', JSON.stringify(todos)); }, [todos]); Result: after checking a todo it stays checked after reload ✅ Learning: !!value coerces to boolean for quick UI checks (checked={!!item.isCompleted}), but the real fix is normalizing your stored data on load so you don’t rely on ad-hoc coercion. Thoughts welcome! #react #javascript #webdev #frontend #100DaysOfCode
More Relevant Posts
-
🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 – 𝗣𝗮𝗿𝘁 𝟮 If you think you understand JavaScript… Try predicting these outputs 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗿𝘂𝗻𝗻𝗶𝗻𝗴 𝘁𝗵𝗲 𝗰𝗼𝗱𝗲 😏 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝘆𝘀𝘁𝗲𝗿𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎); 𝑣𝑎𝑟 𝑎 = 10; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑏); 𝑙𝑒𝑡 𝑏 = 20; 𝗢𝘂𝘁𝗽𝘂𝘁: undefined ReferenceError 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • var is hoisted and initialized with undefined • let is hoisted but stays in 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) 👉 Accessing b before initialization throws an error. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗔𝗰𝘁𝗶𝗼𝗻 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑜𝑢𝑡𝑒𝑟() { 𝑙𝑒𝑡 𝑐𝑜𝑢𝑛𝑡 = 0; 𝑟𝑒𝑡𝑢𝑟𝑛 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑖𝑛𝑛𝑒𝑟() { 𝑐𝑜𝑢𝑛𝑡++; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑐𝑜𝑢𝑛𝑡); }; } 𝑐𝑜𝑛𝑠𝑡 𝑓𝑛 = 𝑜𝑢𝑡𝑒𝑟(); 𝑓𝑛(); 𝑓𝑛(); 𝑓𝑛(); 𝗢𝘂𝘁𝗽𝘂𝘁: 1 2 3 💡 𝗪𝗵𝘆? The inner function forms a 𝗰𝗹𝗼𝘀𝘂𝗿𝗲, remembering count even after outer() has finished execution. 👉 This is heavily used in 𝗥𝗲𝗮𝗰𝘁 𝗵𝗼𝗼𝗸𝘀 & 𝗿𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗮𝗽𝗽𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝗣𝗿𝗼𝗺𝗶𝘀𝗲 𝘃𝘀 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 (𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽) 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑆𝑡𝑎𝑟𝑡"); 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑇𝑖𝑚𝑒𝑜𝑢𝑡"); }, 0); 𝑃𝑟𝑜𝑚𝑖𝑠𝑒.𝑟𝑒𝑠𝑜𝑙𝑣𝑒().𝑡ℎ𝑒𝑛(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑃𝑟𝑜𝑚𝑖𝑠𝑒"); }); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝐸𝑛𝑑"); 𝗢𝘂𝘁𝗽𝘂𝘁: Start End Promise Timeout 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • Promise callbacks go to Microtask Queue • setTimeout goes to Macrotask Queue 👉 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 are executed before 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟰: 𝗧𝗿𝗶𝗰𝗸𝘆 𝗘𝗾𝘂𝗮𝗹𝗶𝘁𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] == 𝑓𝑎𝑙𝑠𝑒); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] === 𝑓𝑎𝑙𝑠𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: true false 💡 𝗪𝗵𝘆? • == allows 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻 • [] → "" → 0 and false → 0 → ✅ true • === checks strict equality (no coercion) → ❌ false 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟱: 𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗧𝗿𝗮𝗽 𝑐𝑜𝑛𝑠𝑡 𝑎 = { 𝑛𝑎𝑚𝑒: "𝐽𝑆" }; 𝑐𝑜𝑛𝑠𝑡 𝑏 = 𝑎; 𝑏.𝑛𝑎𝑚𝑒 = "𝑅𝑒𝑎𝑐𝑡"; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎.𝑛𝑎𝑚𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: React 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 Objects are stored by reference, not value. Both a and b point to the 𝘀𝗮𝗺𝗲 𝗺𝗲𝗺𝗼𝗿𝘆 𝗹𝗼𝗰𝗮𝘁𝗶𝗼𝗻. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 If you can confidently answer these, you're ahead of 𝟴𝟬% 𝗼𝗳 𝗰𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲𝘀. Most developers fail not because they don’t know JavaScript… But because they don’t understand its 𝗰𝗼𝗿𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗱𝗲𝗲𝗽𝗹𝘆. 🔥 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝗳𝗼𝗿 𝗬𝗼𝘂 console.log(typeof null); console.log(typeof NaN); Drop your answers in the comments 👇 ♻️ Follow Shubham Kumar Raj for more such high-value interview content #javascript #frontenddeveloper #codinginterview #webdevelopment #programming #learnjavascript #100daysofcode #hiring
To view or add a comment, sign in
-
#day2 of #javascript 1. Operators in JavaScript 🔹 A. Arithmetic Operators Math operations ke liye use hote hain: let a = 10; let b = 5; console.log(a + b); // 15 (Addition) console.log(a - b); // 5 (Subtraction) console.log(a * b); // 50 (Multiplication) console.log(a / b); // 2 (Division) console.log(a % b); // 0 (Modulus / remainder) 🔹 B. Comparison Operators Compare karte hain (true/false return karte hain): let x = 10; let y = "10"; console.log(x == y); // true (value check) console.log(x === y); // false (value + type check) console.log(x != y); // false console.log(x > 5); // true console.log(x < 5); // false 🔹 C. Logical Operators let age = 20; console.log(age > 18 && age < 25); // true (AND) console.log(age > 18 || age < 10); // true (OR) console.log(!(age > 18)); // false (NOT) 🔀 2. if, else, else if Condition check karne ke liye use hota hai: let marks = 75; if (marks > 90) { console.log("A Grade"); } else if (marks > 60) { console.log("B Grade"); } else { console.log("Fail"); } 🔁 3. switch Statement Multiple conditions ke liye use hota hai: let day = 2; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; default: console.log("Invalid Day"); } 👉 break important hai warna next cases bhi run ho jayenge ⚡ 4. Even / Odd Checker let num = 7; if (num % 2 === 0) { console.log("Even Number"); } else { console.log("Odd Number"); } 🎓 5. Grade Calculator let marks = 85; if (marks >= 90) { console.log("Grade A"); } else if (marks >= 75) { console.log("Grade B"); } else if (marks >= 50) { console.log("Grade C"); } else { console.log("Fail"); } #hardwork #consistency #coding #programming
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 11 Imagine this 👇 You are building an app… And you need to store: User 1 name User 2 name User 3 name User 4 name 😵 Will you create separate variables for each? ```javascript let user1 = "Abhay" let user2 = "Rahul" let user3 = "Aman" ``` This is messy ❌ Not scalable ❌ --- ## 🔥 Solution → Arrays An **Array** is a data structure that allows you to store **multiple values in a single variable** --- ## 🔹 Creating an Array ```javascript let users = ["Abhay", "Rahul", "Aman"] ``` 👉 Now everything is inside one variable --- ## 🔹 Index (Very Important) Every element in an array has an **index** ```javascript let users = ["Abhay", "Rahul", "Aman"] ``` Index: Abhay → 0 Rahul → 1 Aman → 2 👉 Array always starts from **0** --- ## 🔹 Accessing Values ```javascript console.log(users[0]) // Abhay console.log(users[1]) // Rahul ``` --- ## 🔹 Updating Values ```javascript users[1] = "Neha" console.log(users) ``` 👉 Output: ["Abhay", "Neha", "Aman"] --- ## 🔹 Array Length ```javascript console.log(users.length) ``` 👉 Output: 3 📌 Useful when working with loops --- ## 🔹 Real Life Example Think of a **shopping cart 🛒** Instead of: item1 item2 item3 We use: ```javascript let cart = ["Shoes", "T-shirt", "Watch"] ``` 👉 Clean 👉 Organized 👉 Easy to manage --- ## 🔥 Simple Summary Array → multiple values ek jagah Index → position of value Access → users[0] Update → users[1] = "Neha" --- ### 💡 Programming Rule **Group related data together. Arrays make your code clean and scalable.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Scope Explained (Why some variables work… and others don’t) Have you ever faced this? 🤔 if (true) { let a = 10; } console.log(a); // ❌ ReferenceError But then this works… 😳 if (true) { var b = 20; } console.log(b); // ✅ works Why does this happen? 🧠 The answer lies in Scope 👉 Scope defines where variables can be accessed in your code. 📦 Types of Scope: 1️⃣ Global Scope Variables declared outside any function let a = 10; function test() { console.log(a); // ✅ accessible } ✔️ Available everywhere 2️⃣ Function Scope Variables declared inside a function function test() { let b = 20; console.log(b); // ✅ } console.log(b); // ❌ ReferenceError ✔️ Only inside that function 3️⃣ Block Scope Variables inside {} (if, loops, etc.) if (true) { let c = 30; console.log(c); // ✅ } console.log(c); // ❌ ReferenceError ✔️ Works with let and const ❌ var ignores block scope ⚠️ Important Insight: if (true) { var x = 50; } console.log(x); // ✅ works 👉 Because var is function scoped, not block scoped Now let's understand the differences between var, let and const. 1️⃣ Scope 👉 var → Function scoped 👉 let & const → Block scoped if (true) { var x = 10; let y = 20; } console.log(x); // ✅ console.log(y); // ❌ 2️⃣ Redeclaration 👉 var → ✅ Allowed 👉 let & const → ❌ Not allowed var a = 10; var a = 20; // ✅ let b = 10; let b = 20; // ❌ 3️⃣ Reassignment 👉 var → ✅ Allowed 👉 let → ✅ Allowed 👉 const → ❌ Not allowed let a = 10; a = 20; // ✅ const b = 30; b = 40; // ❌ 4️⃣ Hoisting 👉 var → hoisted + initialized (undefined) 👉 let & const → hoisted but NOT initialized (Temporal Dead Zone) console.log(a); // undefined var a = 10; console.log(b); // ❌ ReferenceError let b = 20; 🎯 Best Practices: ✔️ Use const by default ✔️ Use let when value changes ❌ Avoid var in modern JavaScript 🧠 One powerful takeaway: 👉 The difference between var, let, and const is all about scope, hoisting, and reassignment. #JavaScript #FrontendDevelopment #WebDevelopment #Coding #LearnInPublic
To view or add a comment, sign in
-
🔍 𝗔 𝗦𝗶𝗺𝗽𝗹𝗲 𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗿𝗱𝗲𝗿 𝗠𝗶𝘀𝘁𝗮𝗸𝗲 𝗧𝗵𝗮𝘁 𝗖𝗮𝘂𝘀𝗲𝗱 𝘂𝗻𝗱𝗲𝗳𝗶𝗻𝗲𝗱 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗪𝗵𝗶𝗹𝗲 𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗠𝘆 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗖𝗼𝗿𝗲 𝗠𝗩𝗖 𝗖𝗵𝗮𝘁 𝗦𝘆𝘀𝘁𝗲𝗺 Today while working on my 𝙏𝙖𝙨𝙠 𝙈𝙖𝙣𝙖𝙜𝙚𝙢𝙚𝙣𝙩 𝙎𝙮𝙨𝙩𝙚𝙢 𝙥𝙧𝙤𝙟𝙚𝙘𝙩, I encountered an interesting debugging scenario while implementing the 𝙘𝙝𝙖𝙩 𝙞𝙣𝙗𝙤𝙭 𝙛𝙚𝙖𝙩𝙪𝙧𝙚 𝙞𝙣 𝘼𝙎𝙋.𝙉𝙀𝙏 𝘾𝙤𝙧𝙚 𝙈𝙑𝘾. My goal was simple: 👉 Get the 𝙘𝙪𝙧𝙧𝙚𝙣𝙩 𝙡𝙤𝙜𝙜𝙚𝙙-𝙞𝙣 𝙐𝙨𝙚𝙧𝙄𝙙 inside a 𝙨𝙚𝙥𝙖𝙧𝙖𝙩𝙚 𝙅𝙖𝙫𝙖𝙎𝙘𝙧𝙞𝙥𝙩 𝙛𝙞𝙡𝙚 (chatting.js). So I added this Razor code in my view: <script> window.AppConfig = { userId: '@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value' }; </script> Then in my JavaScript file I tried: 𝘤𝑜𝘯𝑠𝘵 𝘤𝑢𝘳𝑟𝘦𝑛𝘵𝑈𝘴𝑒𝘳𝐼𝘥 = 𝘸𝑖𝘯𝑑𝘰𝑤.𝐴𝘱𝑝𝘊𝑜𝘯𝑓𝘪𝑔?.𝘶𝑠𝘦𝑟𝘐𝑑; 𝑐𝘰𝑛𝘴𝑜𝘭𝑒.𝑙𝘰𝑔("𝘊𝑢𝘳𝑟𝘦𝑛𝘵 𝘜𝑠𝘦𝑟 𝐼𝘋:", 𝑐𝘶𝑟𝘳𝑒𝘯𝑡𝘜𝑠𝘦𝑟𝘐𝑑); But the console kept returning: ❌ 𝙪𝙣𝙙𝙚𝙛𝙞𝙣𝙚𝙙 At first it looked like a problem with 𝙘𝙡𝙖𝙞𝙢𝙨 𝙤𝙧 𝙖𝙪𝙩𝙝𝙚𝙣𝙩𝙞𝙘𝙖𝙩𝙞𝙤𝙣, but the real issue was something many developers overlook. 🔎 𝙏𝙝𝙚 𝘼𝙘𝙩𝙪𝙖𝙡 𝙋𝙧𝙤𝙗𝙡𝙚𝙢 My script order looked like this: <𝘴𝘤𝘳𝘪𝘱𝘵 𝘴𝘳𝘤="~/𝘫𝘴/𝘤𝘩𝘢𝘵𝘵𝘪𝘯𝘨.𝘫𝘴"></𝘴𝘤𝘳𝘪𝘱𝘵> <𝘴𝘤𝘳𝘪𝘱𝘵> 𝘸𝘪𝘯𝘥𝘰𝘸.𝘈𝘱𝘱𝘊𝘰𝘯𝘧𝘪𝘨 = { 𝘶𝘴𝘦𝘳𝘐𝘥: '@𝘜𝘴𝘦𝘳.𝘍𝘪𝘯𝘥𝘍𝘪𝘳𝘴𝘵(𝘚𝘺𝘴𝘵𝘦𝘮.𝘚𝘦𝘤𝘶𝘳𝘪𝘵𝘺.𝘊𝘭𝘢𝘪𝘮𝘴.𝘊𝘭𝘢𝘪𝘮𝘛𝘺𝘱𝘦𝘴.𝘕𝘢𝘮𝘦𝘐𝘥𝘦𝘯𝘵𝘪𝘧𝘪𝘦𝘳)?.𝘝𝘢𝘭𝘶𝘦' }; </𝘴𝘤𝘳𝘪𝘱𝘵> Because of this order: 1️⃣ The browser first executed 𝒄𝒉𝒂𝒕𝒕𝒊𝒏𝒈.𝒋𝒔 2️⃣ window.AppConfig 𝒅𝒊𝒅 𝒏𝒐𝒕 𝒆𝒙𝒊𝒔𝒕 𝒚𝒆𝒕 3️⃣ So currentUserId became 𝙪𝙣𝙙𝙚𝙛𝙞𝙣𝙚𝙙 ✅ 𝑻𝒉𝒆 𝑭𝒊𝒙 Simply 𝙞𝙣𝙞𝙩𝙞𝙖𝙡𝙞𝙯𝙚 𝙩𝙝𝙚 𝙜𝙡𝙤𝙗𝙖𝙡 𝙘𝙤𝙣𝙛𝙞𝙜𝙪𝙧𝙖𝙩𝙞𝙤𝙣 𝙗𝙚𝙛𝙤𝙧𝙚 𝙡𝙤𝙖𝙙𝙞𝙣𝙜 𝙩𝙝𝙚 𝙅𝙎 𝙛𝙞𝙡𝙚. <𝘴𝘤𝘳𝘪𝘱𝘵> 𝘸𝘪𝘯𝘥𝘰𝘸.𝘈𝘱𝘱𝘊𝘰𝘯𝘧𝘪𝘨 = { 𝘶𝘴𝘦𝘳𝘐𝘥: '@𝘜𝘴𝘦𝘳.𝘍𝘪𝘯𝘥𝘍𝘪𝘳𝘴𝘵(𝘚𝘺𝘴𝘵𝘦𝘮.𝘚𝘦𝘤𝘶𝘳𝘪𝘵𝘺.𝘊𝘭𝘢𝘪𝘮𝘴.𝘊𝘭𝘢𝘪𝘮𝘛𝘺𝘱𝘦𝘴.𝘕𝘢𝘮𝘦𝘐𝘥𝘦𝘯𝘵𝘪𝘧𝘪𝘦𝘳)?.𝘝𝘢𝘭𝘶𝘦' }; <𝘴𝘤𝘳𝘪𝘱𝘵 𝘴𝘳𝘤="~/𝘫𝘴/𝘤𝘩𝘢𝘵𝘵𝘪𝘯𝘨.𝘫𝘴"></𝘴𝘤𝘳𝘪𝘱𝘵> Now the script file can correctly access: window.AppConfig.userId 💡 𝑲𝙚𝒚 𝑳𝙚𝒔𝙨𝒐𝙣 When passing 𝙨𝙚𝙧𝙫𝙚𝙧-𝙨𝙞𝙙𝙚 𝙍𝙖𝙯𝙤𝙧 𝙙𝙖𝙩𝙖 𝙩𝙤 𝙚𝙭𝙩𝙚𝙧𝙣𝙖𝙡 𝙅𝙖𝙫𝙖𝙎𝙘𝙧𝙞𝙥𝙩 𝙛𝙞𝙡𝙚𝙨, always ensure: ✔ Server values are 𝙞𝙣𝙞𝙩𝙞𝙖𝙡𝙞𝙯𝙚𝙙 𝙛𝙞𝙧𝙨𝙩 ✔ Then load your 𝙚𝙭𝙩𝙚𝙧𝙣𝙖𝙡 𝙅𝙎 𝙨𝙘𝙧𝙞𝙥𝙩𝙨 Small ordering issues like this can easily lead to confusing 𝙪𝙣𝙙𝙚𝙛𝙞𝙣𝙚𝙙 𝙗𝙪𝙜𝙨. Debugging these little things is part of the journey that slowly turns a developer into a 𝙗𝙚𝙩𝙩𝙚𝙧 𝙥𝙧𝙤𝙗𝙡𝙚𝙢 𝙨𝙤𝙡𝙫𝙚𝙧. Every bug teaches something. 💡 #DotNet #AspNetCore #CSharp #WebDevelopment #JavaScript #SoftwareDevelopment #Debugging #Programming #DotNetDeveloper #BackendDevelopment #FullStackDevelopment #DevelopersLife #LearningInPublic #TechJourney #ITCareers #HiringDevelopers #HRTech
To view or add a comment, sign in
-
-
🔥 Why Your Node.js API is Slow (And You Don't Know It) Most developers don't understand the Event Loop. Result: Their APIs are 10x slower than they should be. ❌ The Problem: javascript // BLOCKING - Event loop gets stuck app.get('/users', async (req, res) => { for (let i = 0; i < 1000; i++) { await db.query('SELECT * FROM users WHERE id = ?', i); } res.send(users); }); // Response time: 5 seconds 🐢 Why slow? Query 1 completes, then Query 2 starts Sequential = 1000 queries = slow death Event loop blocked waiting for each query ✅ The Fix: javascript // NON-BLOCKING - Parallel execution app.get('/users', async (req, res) => { const queries = []; for (let i = 0; i < 1000; i++) { queries.push(db.query('SELECT * FROM users WHERE id = ?', i)); } const users = await Promise.all(queries); res.send(users); }); // Response time: 500ms 🚀 What changed? All 1000 queries start immediately They run in parallel (not sequential) Promise.all() waits for all to complete 10x faster! 🔑 The Core Concept: Node.js Event Loop: Execute synchronous code Handle I/O operations (non-blocking) Return to step 1 If you force it to wait (blocking), you're wasting its superpowers. 💡 Real-World Scenarios: DATABASE QUERIES: ❌ for loop with await → sequential ✅ Promise.all() → parallel FILE OPERATIONS: ❌ fs.readFileSync() → blocks everything ✅ fs.promises.readFile() → non-blocking API CALLS: ❌ await fetch() then await fetch() → slow ✅ Promise.all([fetch(), fetch()]) → fast 🎯 Performance Gains: Scenario: Fetching 100 user records Sequential (❌): Each query: 50ms Total: 100 × 50ms = 5000ms (5 sec) Parallel (✅): All queries: 50ms Total: 50ms (database limits you) 100x faster! ⚡ Pro Tips: Use Promise.all() for independent operations Use Promise.allSettled() if some can fail Batch operations (don't query 1000 times) Connection pooling (reuse DB connections) Never use synchronous I/O (readFileSync, etc) 🔧 Quick Audit: Check your code: Any 'for' loops with 'await'? ❌ Fix it Any readFileSync()? ❌ Replace with async Any sequential API calls? ❌ Parallelize Real talk: I found 3 bottlenecks in my codebase doing this audit. Fixed them in 2 hours. API went 5x faster. What's your biggest Node.js performance issue? #NodeJS #Performance #BackendDevelopment #JavaScript #Optimization #WebDevelopment
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 12 Yesterday we learned Arrays… But storing data is not enough. 👉 Real power comes when you modify data Imagine this 👇 You have a shopping cart 🛒 Add item Remove item Update item Will you do everything manually? ❌ This is where Array Methods come in. 🔹 1. push() → Add item at the end let cart = ["Shoes", "T-shirt"] cart.push("Watch") console.log(cart) 👉 Output: ["Shoes", "T-shirt", "Watch"] 📌 Adds item at the end 🔹 2. pop() → Remove last item cart.pop() console.log(cart) 👉 Output: ["Shoes", "T-shirt"] 📌 Removes item from the end 🔹 3. unshift() → Add item at the beginning cart.unshift("Cap") console.log(cart) 👉 Output: ["Cap", "Shoes", "T-shirt"] 📌 Adds item at the start 🔹 4. shift() → Remove first item cart.shift() console.log(cart) 👉 Output: ["Shoes", "T-shirt"] 📌 Removes item from the start 🔥 Real Life Flow Shopping cart example: Add item → push() Remove last item → pop() Add priority item → unshift() Remove first item → shift() 🔥 Simple Summary push → add end pop → remove end unshift → add start shift → remove start 💡 Programming Rule Don’t manipulate data manually. Use built-in methods. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods (push, pop, shift, unshift) Day 13 → Array Iteration (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
In JavaScript, we often use if...else if...else chain to handle conditions. But, there is a cleaner way to write this code, objects. For example, look at the following code: for (tab in issueElems) { if (tab === "open") { openIssues.innerHTML = ""; openCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, openIssuesSpinner); } else if (tab === "closed") { closedIssues.innerHTML = ""; closedCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, closedIssuesSpinner); } else { allIssues.innerHTML = ""; allCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, allIssuesSpinner); } } Now, if we define an object like the following beforehand: let issueElems = { all: { count: allIssuesCount, issues: allIssues, spinner: allIssuesSpinner, }, open: { count: openIssuesCount, issues: openIssues, spinner: openIssuesSpinner, tab: openTab, }, closed: { count: closedIssuesCount, issues: closedIssues, spinner: closedIssuesSpinner, tab: closedTab, }, }; The code becomes as simple as this: for (tab in issueElems) { let c = issueElems[tab]; c.issues.innerHTML = ""; c.count.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, c.spinner); } There is also switch...case, but it works in a very absurd way. If you don't add break to case clauses, it keeps going to the next case clause. It starts with the first matching case clause and continues until the break statement is encountered. That's why objects are the best way to handle this matter. What do you use? Share your ideas!
To view or add a comment, sign in
-
How do you deep clone an object in JavaScript? If you answered JSON.parse(JSON.stringify(obj)), you're not alone. It's been the go-to hack for over a decade. But it's broken in ways that will bite you at the worst possible time. const original = { name: "Pranjul", joined: new Date("2024-01-01"), skills: new Set(["React", "CSS", "TypeScript"]) }; const cloned = JSON.parse(JSON.stringify(original)); console.log(cloned.joined); // "2024-01-01T00:00:00.000Z" (string, NOT a Date) console.log(cloned.skills); // {} (empty object, NOT a Set) Everything silently broke. No errors and warnings. Your Date is now a string. Your Set is an empty object. And your code downstream has no idea. This is why structuredClone() exists. const cloned = structuredClone(original); console.log(cloned.joined); // Date object (correct!) console.log(cloned.skills); // Set {"React", "CSS", "TypeScript"} (correct!) One function call. Everything cloned properly. Let me highlight that circular reference row: const obj = { name: "Pranjul" }; obj.self = obj; // circular reference JSON.parse(JSON.stringify(obj)); // TypeError: Converting circular structure to JSON structuredClone(obj); // Works perfectly. Returns a proper deep clone. If you've ever hit that circular reference error in production, you know how painful it is. structuredClone just handles it. When JSON.parse/stringify still wins: There is one scenario where the JSON approach has an advantage: speed for simple, flat objects with only strings and numbers. The JSON functions are heavily optimized in V8. For this kind of data, JSON is faster: const simpleData = { id: 1, name: "Pranjul", active: true, tags: ["frontend", "react"] }; But the moment you have Dates, Sets, Maps, undefined, or nested structures, structuredClone is the correct choice. What structuredClone CANNOT clone: Not everything is supported. Functions and DOM nodes can't be cloned. Class instances get cloned as plain objects and lose their methods. That's by design. My rule of thumb: ✅ Need to clone plain data with possible Dates/Sets/Maps? Use structuredClone ✅ Need to serialize data for storage or network? Use JSON.stringify ✅ Need to clone class instances with methods? Write a custom clone method structuredClone ships in every modern browser and Node.js 17+. There's no reason to keep using the JSON hack for deep cloning in 2026. What's a JavaScript built-in that you learned about way too late? Share below 👇 w3schools.com JavaScript Mastery JavaScript Developer Frontend Masters
To view or add a comment, sign in
-
-
Next.js 16 Migration Alert: How to update your Utility Functions for Async Requests 🛠️ If you are upgrading to Next.js 16, your "traditional" utility functions are likely about to break. With Async Request APIs now standardized, params, searchParams, cookies(), and headers() are all Promises. This is a fundamental shift for the React Compiler to optimize rendering. Here is how to refactor your code to stay compliant. 1️⃣ The "Utility Function" Refactor Previously, you could pass params into a helper function and access them immediately. In v16, you must handle the Promise. ❌ Old Way (v14/v15): function getCategory(params) { return params.category; // This will now be undefined or error } ✅ New Way (v16): async function getCategory(params: Promise<{ category: string }>) { const { category } = await params; return category; } 2️⃣ Handling cookies() and headers() These are no longer static snapshots. They are dynamic functions that must be awaited at the point of use to avoid blocking the entire route's execution. ❌ Deprecated: const cookieStore = cookies(); const theme = cookieStore.get('theme'); ✅ Next.js 16 Standard: const cookieStore = await cookies(); const theme = cookieStore.get('theme'); 3️⃣ The Pattern: "Pass-Through" vs. "Awaited" To keep your components clean, decide where you want to resolve the Promise. Option A (In Page): Await the params in the Page component and pass the values down to children. (Best for simple props). Option B (In Component): Pass the Promise down and let the child component use() it or await it. (Best for deep component trees). // app/shop/[id]/page.tsx export default function Page({ params }) { // Pass the promise directly to a Client Component return <ProductDetails params={params} />; } 🚀 Migration Checklist: [ ] Search for all instances of params and searchParams in your Page and Layout files. [ ] Update TypeScript interfaces to use Promise<T>. [ ] Audit your Middleware—if you were doing complex body manipulation, migrate that logic to proxy.ts or Route Handlers. [ ] Ensure every Parallel Route (@folder) has a default.js to prevent 404s during navigation. The Strategy: Don't fight the async nature of Next.js 16. By embracing await, you allow the React Compiler to "hole-punch" your UI—rendering static content instantly while the dynamic parts catch up. How is your team handling the v16 migration? Are you automating the refactor with Codemods, or doing a manual audit? comment 👇 #NextJS16 #ReactJS #WebDevelopment #CodingLife #SoftwareArchitecture #TypeScript #Vercel #Frontend
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