Why delete Works Here… But Not There This morning’s code was: let x = 10; const obj = { x: 20 }; delete x; delete obj.x; console.log(x); console.log(obj.x); 💡 Correct Output 10 undefined 🧠 Simple Explanation : 🔹 Line 1: delete x; Here’s the important rule 👇 👉 delete cannot remove variables declared with let, const, or var. So this line: delete x; does nothing. x still exists with value 10. ✔ Output: 10 🔹 Line 2: delete obj.x; Now this is different 👀 obj.x is a property of an object delete can remove object properties So after: delete obj.x; The property x no longer exists on obj. Accessing it returns: undefined ✔ Output: undefined 🎯 Key Takeaways : delete ❌ does NOT work on variables delete ✅ works on object properties Removing a property ≠ setting it to undefined let / const variables are protected from deletion 📌 That’s why delete is mostly used with objects, not variables. 💬 Your Turn Did you expect both deletes to work? 😄 Comment “Surprised 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Objects #TechWithVeera #WebDevelopment
JavaScript delete operator: variables vs object properties
More Relevant Posts
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟵 Have you ever updated one variable… and another one changed automatically? 𝙋𝙖𝙪𝙨𝙚 𝙛𝙤𝙧 𝙖 𝙨𝙚𝙘𝙤𝙣𝙙 — 𝙬𝙤𝙪𝙡𝙙 𝙮𝙤𝙪 𝙚𝙭𝙥𝙚𝙘𝙩 𝙩𝙝𝙞𝙨 𝙘𝙤𝙙𝙚 𝙩𝙤 𝙢𝙪𝙩𝙖𝙩𝙚 𝙗𝙤𝙩𝙝 𝙫𝙖𝙡𝙪𝙚𝙨? { 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟷 = { 𝚗𝚊𝚖𝚎: "𝙰𝚕𝚎𝚡" }; 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟸 = 𝚞𝚜𝚎𝚛𝟷; 𝚞𝚜𝚎𝚛𝟸.𝚗𝚊𝚖𝚎 = "𝙹𝚘𝚑𝚗"; 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚞𝚜𝚎𝚛𝟷.𝚗𝚊𝚖𝚎); // "𝙹𝚘𝚑𝚗" } Why did user1 change? Because: • Both variables point to the same memory address • No copy was created • Only the reference was shared 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵’𝘴 𝘝𝘢𝘭𝘶𝘦 𝘷𝘴 𝘙𝘦𝘧𝘦𝘳𝘦𝘯𝘤𝘦 𝘣𝘦𝘩𝘢𝘷𝘪𝘰𝘳 — 𝘢𝘯𝘥 𝘪𝘵’𝘴 𝘥𝘦𝘦𝘱𝘭𝘺 𝘵𝘪𝘦𝘥 𝘵𝘰 𝘮𝘦𝘮𝘰𝘳𝘺. 𝙏𝙝𝙚 𝙈𝙚𝙣𝙩𝙖𝙡 𝙈𝙤𝙙𝙚𝙡 (𝙈𝙚𝙢𝙤𝙧𝙮 𝙁𝙞𝙧𝙨𝙩) JavaScript mainly uses two memory areas: -> Stack Memory • Stores primitive values • Fixed size • Fast access -> Heap Memory • Stores objects, arrays, functions • Dynamic size • Accessed via references 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙫𝙖𝙡𝙪𝙚: A copy of the actual value is passed. Primitives (number, string, boolean, null, undefined, symbol) are always passed by value. 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙧𝙚𝙛𝙚𝙧𝙚𝙣𝙘𝙚: A memory address (reference) is passed, not the object itself. Objects & arrays live in heap memory. #JavaScript #JSFundamentals #MemoryManagement #FrontendDevelopment #ReactJS #BugFixing #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
I deleted every index.ts file in my project. Here is why. 🗑️ For years, I was obsessed with "Clean Imports." I wanted my code to look like this: import { Button, Input, Modal } from './components'; So I created an index.ts (Barrel File) in every folder to re-export everything. It felt satisfying. It felt organized. Then my project grew. 📈 Suddenly, I started hitting weird issues: 1. Jest tests got slow: I would test a simple Button, but Jest would crash because the index.ts was also trying to load the Modal (which had a huge library dependency). 2. Circular Dependencies: Module A imports from index, which imports Module B, which imports Module A... infinite loop. 🔄 3. Broken Tree-Shaking: Webpack/Vite struggled to remove unused code because the Barrel file linked everything together. ❌ The Trap (Left Image): Barrel files force your tooling to process every single file in a folder, even if you only need one small function. ✅ The Fix (Right Image): Direct Imports. import { Button } from './components/Button'; Yes, the import path is slightly longer. But in exchange, you get: * Faster CI/CD pipelines. ⚡ * Instant unit tests. * Zero circular dependency errors. "Clean code" isn't just about how it looks. It's about how it runs. Are you still using Barrel Files, or have you banned them too? 👇 #TypeScript #React #WebPerformance #SoftwareArchitecture #FrontendEngineering #CodingBestPractices #JavaScript #Vite #DeveloperExperience
To view or add a comment, sign in
-
-
Consistency > excuses. That’s today’s win. Day 10 | JavaScript – Objects Yesterday I missed posting. Today, I didn’t repeat that mistake. After getting comfortable with functions, I moved into objects — a cleaner and more powerful way to store related data. What I learned today: 1. Creating objects using { } 2. Storing data as key–value pairs 3. Accessing: -the whole object -individual properties using dot (.) notation 4. Updating values by reassigning properties 5. Removing properties completely using the delete keyword Objects made it clear how JavaScript organizes real-world data — not just values, but structure. Learning. Day 10 done. #JavaScript #Objects #LearningInPublic #WebDevelopment #DeveloperJourney
To view or add a comment, sign in
-
🚀 LeetCode: Two Sum II - Input Array Is Sorted The goal is to find two numbers in a 1-indexed sorted array that add up to a specific target sum. Since the array is already sorted, we can find the indices efficiently without extra storage. 🛠️ My Approach 1. Initialization: I used two pointers, i starting at the beginning (index 0) and j at the end of the array. 🔡 2. Sorted Property Leverage: Instead of a nested loop, I compared the sum of elements at i and j to the target. If the sum is too high, I decrement j; if it's too low, I increment i. 🧹 3. Two-Pointer Optimization: By narrowing the window from both sides, I found the exact pair in a single pass. 📍 4. One pointer moves from the start (i), and the other from the end (j). ❌ If the sum matches the target, we return the 1-indexed positions [i + 1, j + 1] and break the loop. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(1) #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗦𝗨𝗥𝗣𝗥𝗜𝗦𝗜𝗡𝗚 𝗧𝗥𝗨𝗧𝗛 𝗔𝗕𝗢𝗨𝗧 𝗝𝗔𝗩𝗔𝗦𝗖𝗥𝗜𝗣𝗧'𝗦 𝗠𝗔𝗣 𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡 You use JavaScript to solve problems. But do you know how map() works? - It passes the current element to the callback - It passes the current index to the callback - It passes the entire array to the callback What happens when you use arr.map(parseInt)? - The index gets passed as the radix - This causes unexpected parsing behavior Let's look at an example: const arr = ['1', '7', '11']; const result = arr.map(parseInt); console.log(result); The output is: [1, NaN, 3] This happens because: - parseInt('1', 0) defaults to base 10 and returns 1 - parseInt('7', 1) returns NaN because base 1 is invalid - parseInt('11', 2) returns 3 because '11' in binary is 3 To avoid this issue: - Use an arrow function wrapper: arr.map(x => parseInt(x, 10)) - Use the Number constructor: arr.map(Number) - Use the unary plus operator: arr.map(x => +x) Remember: always be explicit about what you're passing to a function. Source: https://lnkd.in/gQz8P-Tv
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗼𝗳 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You use closures in JavaScript every day. They're in every callback, event handler, and setTimeout. But what are closures, and how do they work? A closure is a function that has access to its own scope and the scope of its outer functions. This allows it to "remember" variables from its surrounding environment even when the outer function has returned. Here's an example: - Create a counter function that returns an increment function. - The increment function has access to the counter variable even after the counter function has returned. This works because the increment function "closes over" the counter variable, keeping it alive even after the counter function has finished executing. Closures are powerful for creating private state and function factories. They're also used in memoization and caching. However, closures can cause memory leaks if not used carefully. To avoid this, make sure to only capture the variables you need, and avoid creating unnecessary closures. Understanding closures will help you: - Debug scope-related bugs - Avoid memory leaks - Write more efficient code - Understand advanced patterns like React hooks and module patterns Source: https://lnkd.in/gJHhS23p
To view or add a comment, sign in
-
🌙 Evening Post — Explanation & Answer ✅ Why This Map Has Two Entries This morning’s code was: const map = new Map(); map.set({}, "first"); map.set({}, "second"); console.log(map.size); 💡 Correct Output 2 Yes — two entries, not one 😄 Here’s why 👇 🧠 Simple Explanation : 🔹 Objects are compared by reference, not by value Even though both keys look like {}: {} !== {} Each {} creates a new object in memory. So JavaScript sees this as: Key 1 → one object reference Key 2 → another object reference They are completely different keys. 🔹 How Map works Map allows any type as a key Keys are matched by reference Different object references → different entries So: map.size // 2 🎯 Key Takeaways : Map keys are compared by reference {} and {} are never the same key Objects are not value-equal by default This behavior is different from plain objects 📌 To use the same key, you must reuse the same reference: const key = {}; map.set(key, "first"); map.set(key, "second"); 💬 Your Turn Did you expect the size to be 1 or 2? 😄 Comment “Got it wrong 😅” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Maps #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
🌙 Evening Post — Understanding This reduce() Output Clearly This morning’s code was: const result = [1, 2, 3].reduce((acc, curr) => { return acc + curr * 2; }, 0); console.log(result); 💡 Correct Output 12 Now let’s understand why 👇 🧠 Simple Explanation : 🔹 Step 1: Initial value }, 0); acc starts with 0 🔹 Step 2: How reduce() works reduce() runs one element at a time, carrying the result forward. Expression used every time: acc + curr * 2 ⚠️ Important: 👉 Multiplication happens before addition (* has higher precedence than +) 🔹 Step-by-step calculation Array: [1, 2, 3] 1️⃣ First iteration acc = 0 curr = 1 acc + curr * 2 0 + (1 * 2) = 2 2️⃣ Second iteration acc = 2 curr = 2 2 + (2 * 2) = 6 3️⃣ Third iteration acc = 6 curr = 3 6 + (3 * 2) = 12 🎯 Final Result 12 🎯 Key Takeaways : reduce() works left to right acc carries the result forward Operator precedence matters inside reduce curr * 2 runs before acc + 📌 Many wrong answers come from doing: (acc + curr) * 2 ❌ But JavaScript actually does: acc + (curr * 2) ✅ 💬 Your Turn Did you calculate it step by step or mentally? 😄 Comment “Step by step 👍” or “Did it in my head 😅” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
𝗧𝗜𝗟: 𝗛𝗼𝘄 𝗡𝗲𝘀𝘁𝗝𝗦 𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗜𝗻𝗷𝗲𝗰𝘁𝗶𝗼𝗻 𝘀𝘄𝗶𝘁𝗰𝗵𝗲𝘀 𝗺𝗼𝗰𝗸𝘀 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗰𝗵𝗮𝗻𝗴𝗶𝗻𝗴 𝗶𝗺𝗽𝗼𝗿𝘁𝘀 I had an important realization about how dependency injection works in NestJS. 𝗧𝗵𝗲 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗼𝗻 We had 𝘁𝘄𝗼 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻𝘀 of the same service: - one real implementation - one mock implementation (in a separate file) Yet in our service, the code looked like this: import { AbcService } from './abc.service' ; constructor (private abcService: AbcService) {} But I knew we also had mock implementations. So, the obvious question was: where is the mock imported from? How does NestJS decide which one to use? 𝗪𝗵𝗮𝘁 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 In NestJS, an import gives you two things: A 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝘁𝘆𝗽𝗲 (for compile-time checks) A 𝗗𝗜 𝘁𝗼𝗸𝗲𝗻 (used by NestJS at runtime) The actual instance is 𝗻𝗼𝘁 decided by the import. It’s decided in the 𝗺𝗼𝗱𝘂𝗹𝗲 𝗽𝗿𝗼𝘃𝗶𝗱𝗲𝗿 𝗰𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻. { provide: AbcService, // token useFactory: (config) => { if (config.get('mockMode')) { return new MockAbcService(); // from mock file } return new AbcService(); // from real file }, } - The module decides whether to inject the real or mock implementation. - This is what makes DI powerful in NestJS—clean testing, environment-based behavior, and zero changes to consumer code. #NestJS #DependencyInjection #TypeScript #BackendEngineering #SoftwareEngineering
To view or add a comment, sign in
-
-
✅ Solved LeetCode: Path Sum (112) — Alternative Approach Implemented a clean recursive (top-down) DFS solution in JavaScript using a subtractive strategy. Approach: - If the node is null, return false. - If the node is a leaf node, simply check: - root.val === targetSum - Otherwise: - Recursively call the function on left and right subtrees. - Pass targetSum - root.val to reduce the remaining required sum. - Return leftResult || rightResult. This approach eliminates the need for an external variable and keeps the recursion concise and expressive. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A clean divide-and-conquer way to solve Path Sum efficiently! 🌳
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