𝗤𝘂𝗶𝗰𝗸 𝘁𝗶𝗽: 𝗡𝗲𝘃𝗲𝗿 𝗿𝗲𝘁𝘂𝗿𝗻 𝗻𝘂𝗹𝗹. 𝗥𝗲𝘁𝘂𝗿𝗻 𝗲𝗺𝗽𝘁𝘆 𝗮𝗿𝗿𝗮𝘆𝘀. ✅ Stop returning null when a list has no results. Return an empty array instead. 𝗕𝗮𝗱: function getUsers() { return users.length > 0 ? users : null; } 𝗚𝗼𝗼𝗱: function getUsers() { return users || []; } 𝗪𝗵𝘆 𝗶𝘁 𝗺𝗮𝘁𝘁𝗲𝗿𝘀: ❌ Null forces every caller to check before iterating ❌ Leads to "Cannot read property of null" crashes ❌ Creates defensive code everywhere ❌ Makes chaining operations impossible ✅ Empty arrays can be iterated safely (zero loops, no crash) ✅ Works with map, filter, reduce without checks ✅ Cleaner code throughout your application Same applies to objects: return {} instead of null when appropriate. Let your data structures be forgiving. Your team will thank you. 🙏 . . . #JavaScript #BestPractices #CleanCode #WebDevelopment #Programming
★ Devansh P.’s Post
More Relevant Posts
-
One of the simplest ways to write cleaner and more maintainable code is to follow the DRY principle: Don’t Repeat Yourself. If you find yourself copying the same logic in multiple places, that’s usually a sign that it should be moved into a reusable function, component, or module. Instead of this:- if (user.role === "admin") { // admin logic } if (manager.role === "admin") { // admin logic } Think like this:- function isAdmin(role) { return role === "admin"; } Why DRY matters:- - Less duplicated code - Easier maintenance - Fewer bugs - Better readability - Faster updates When logic lives in one place, changes become easier and safer. Write once, reuse often. That’s how scalable code is built. #Programming #CleanCode #DRY #WebDevelopment #JavaScript #SoftwareEngineering #CodingBestPractices
To view or add a comment, sign in
-
-
LeetCode Day 21 : Problem 209 (Minimum Size Subarray Sum) Just solved my LeetCode problem for today. It was "Minimum Size Subarray Sum", find the shortest contiguous subarray whose sum is greater than or equal to a target. My first approach was trying to trim the array from both ends. Remove elements from the front if the sum still holds, then figure out the length at the end. It felt logical in my head but it failed on most test cases and I couldn't immediately see why. The bugs were deeper than I expected. The first one was a JavaScript gotcha that had nothing to do with the algorithm. I wrote newArr = nums thinking I was making a copy. I wasn't. Both variables pointed to the same array in memory, so when I called shift() on newArr, I was also mutating nums mid-loop. The loop was iterating over an array that was shrinking underneath it, silently skipping elements. The second issue was the trimming logic itself. I was only ever looking at the first element when deciding what to remove. That is not how you find a minimal window. You need to consider every possible left boundary, not just the front of the array at that moment. The third was a line I wrote thinking it was doing something: newArr.unshift() with no argument. It adds nothing, returns the length, and the result goes nowhere. Completely dead code that I mistook for a shrink operation. The correct approach is a dynamic sliding window. Expand the right pointer freely. The moment your window sum meets the target, record the length and shrink from the left. Keep shrinking as long as the condition still holds. The smallest window you ever record is your answer. The subtle difference from a longest-window problem is where you record the answer. Here it goes inside the shrink loop, before you remove the left element, because you want the smallest valid window not the largest. The real lesson? Mutating an array while iterating over it is one of the most silent bugs in JavaScript. Always copy with slice or spread when you need an independent array. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
Everyone jokes that the hardest part of programming is naming things, but honestly... it's just the truth. I can spin up a backend, connect a database, and get API routes working fast. But then I'll sit there for minutes completely paralyzed trying to decide if an array should be users, userList, userData, or userArray. (And let's not even talk about trying to name CSS wrapper divs). What’s the worst or weirdest variable name you’ve ever run into in a codebase? I know you guys have seen some bad ones 😂 #webdev #javascript #programming #developerlife
To view or add a comment, sign in
-
Markdown rendering seemed easy. Until I shipped it to production. Users started posting. And then: - Formatting broke in weird ways - HTML tags appeared in random places - Security scans flagged XSS vulnerabilities I spent days building sanitization, handling edge cases, and patching holes. So I built an API to solve this once and for all. It converts Markdown → clean HTML and sanitizes everything automatically. No scripts. No unsafe tags. No surprises. Now I use it for: - User comments and posts (safely) - Rendering docs and README files - Building editors with real-time preview Saves hours of debugging and security headaches. Want to try it? Link in comments. Code "REQUIEMSLAUNCH" gets you 50% off this month. #API #Developers #SoftwareDevelopment #APIDevelopment #Programming #WebDevelopment #DevTools #Tech #Coding
To view or add a comment, sign in
-
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Array.reduce() for Accumulation Let’s dive into how Array.reduce() can simplify your data accumulation tasks. Have you used it before? #javascript #programming #webdevelopment #codingtips ────────────────────────────── Core Concept Array.reduce() is a powerful method for transforming an array into a single value. Have you ever struggled with accumulating values from an array? This method can make that task easier! Key Rules • The first parameter is a callback function that processes each element. • The second parameter is the initial value for the accumulator. • Always return the updated accumulator at the end of your callback function. 💡 Try This const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 10 ❓ Quick Quiz Q: What does the reduce method return? A: It returns a single accumulated value from the array. 🔑 Key Takeaway Use Array.reduce() to streamline your data accumulation and simplify your code!
To view or add a comment, sign in
-
LeetCode Day 19 : Problem 167 (Two Sum II - Input Array Is Sorted) Just solved my LeetCode problem for today. It was "Two Sum II", sorted array, constant space, find two numbers that add up to a target. Sounds like a simple two-pointer problem, right? But here's what I actually learned: My first instinct was to write three separate while loops, each moving a different pointer in a different direction, thinking I was covering all the cases. I wasn't. The bugs were layered. The first loop only moved the right pointer. The second only moved the left. The third moved both but only toward the center. No single loop ever explored the full space of valid pairs. There was also a check I wrote: if (arr !== undefined) return arr. Looked like a guard. Did absolutely nothing. An empty array is never undefined in JavaScript. The condition was always true and I never noticed. The real fix wasn't patching the loops. It was understanding why the sorted order makes three loops completely unnecessary. The two-pointer solution: start left at index 0, right at the last index. If the sum is too small, move left forward. If the sum is too big, move right backward. One loop, every pair covered, O(n) time, O(1) space. The sorted order is the key insight. It guarantees you never need to backtrack, which is exactly why one clean loop beats three broken ones. The real lesson? When your instinct is to add more loops to cover more cases, stop. Ask whether the structure of the data already tells you which direction to move. Sometimes the constraint in the problem is the solution. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
'𝘄𝗼𝗿𝗸𝗲𝗿_𝘁𝗵𝗿𝗲𝗮𝗱𝘀' 𝗱𝗼 𝗻𝗼𝘁 𝗵𝗮𝘃𝗲 𝘁𝗵𝗲 𝘀𝗮𝗺𝗲 𝗝𝗦 𝗵𝗲𝗮𝗽 𝗮𝘀 𝘁𝗵𝗲 𝗺𝗮𝗶𝗻 𝘁𝗵𝗿𝗲𝗮𝗱. As mentioned above, 𝗪𝗼𝗿𝗸𝗲𝗿𝘀 𝗿𝘂𝗻 𝗶𝗻𝘀𝗶𝗱𝗲 𝘁𝗵𝗲𝗶𝗿 𝗼𝘄𝗻 𝗩𝟴 𝗶𝘀𝗼𝗹𝗮𝘁𝗲 which has 𝗮 𝘀𝗲𝗽𝗮𝗿𝗮𝘁𝗲 𝗺𝗲𝗺𝗼𝗿𝘆 𝗹𝗶𝗺𝗶𝘁. Therefore, raising the memory limit for the main process via `--max-old-space-size` does not mean that the 𝗪𝗼𝗿𝗸𝗲𝗿𝘀 𝗴𝗲𝘁 𝗮𝗱𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗺𝗲𝗺𝗼𝗿𝘆 𝘁𝗼𝗼. It makes a difference in case when the application does something heavy - like parsing PDF files. We could 𝗱𝗲𝗳𝗶𝗻𝗲 𝘁𝗵𝗲 𝗵𝗲𝗮𝗽 𝘀𝗶𝘇𝗲 𝘁𝗵𝗮𝘁 𝘁𝗵𝗲 𝗪𝗼𝗿𝗸𝗲𝗿 𝘄𝗼𝘂𝗹𝗱 𝘂𝘀𝗲 import { Worker } from "worker_threads"; new Worker(new URL("./heavy-job-worker.js", import.meta.url), { resourceLimits: { maxOldGenerationSizeMb: 4096, }, }); When working with large PDF files and 𝗽𝗲𝗿𝗳𝗼𝗿𝗺𝗶𝗻𝗴 𝗵𝗲𝗮𝘃𝘆 𝗼𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗹𝗶𝗸𝗲 𝗱𝗮𝘁𝗮 𝗽𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴, this could be useful. #NodeJS #JavaScript #BackendDevelopment #SoftwareEngineering #WebDevelopment #V8 #Performance #Scalability #Multithreading #WorkerThreads #SystemDesign #Programming #Coding
To view or add a comment, sign in
-
Solved a classic sliding window problem today — and it finally clicked for me. The problem: given a binary array, you can flip at most k zeros. Find the longest subarray of 1s. At first glance it looks like a brute force problem. Try every subarray. But that's O(n²). The insight? Think of it like a bouncer at a club with a strict rule: at most k troublemakers (zeros) allowed inside at any time. → right pointer = front door, letting new people in → left pointer = back door, kicking people out when the rule is violated → zeros counter = troublemaker count The window only ever grows when things are clean. When zeros > k, we shrink from the left until we're back in bounds. We never shrink smaller than our best size — that's the key. Result: O(n) time, O(1) space. function maxConsecutiveOnes(nums, k) { let left = 0, zeros = 0, maxLen = 0 for (let right = 0; right < nums.length; right++) { if (nums[right] === 0) zeros++ while (zeros > k) { if (nums[left] === 0) zeros-- left++ } maxLen = Math.max(maxLen, right - left + 1) } return maxLen } // Input: [1,1,1,0,0,0,1,1,1,1,0], k=2 // Output: 6 Sliding window is one of those patterns that once you see it, you see it everywhere — longest substring, max sum subarray, minimum window substring. What DSA pattern took the longest for you to truly internalize? #DSA #JavaScript #SlidingWindow #LeetCode #CodingInterview #ProblemSolving #WebDevelopment #Programming #100DaysOfCode #FrontendDeveloper
To view or add a comment, sign in
-
LeetCode Day 10 : Problem 380 (Insert Delete GetRandom O(1)) Just solved my tenth LeetCode problem. It was "Insert Delete GetRandom O(1)", sounds like a basic Set problem, right? But here's what I actually learned: My first attempt used only a Map. Insert and remove worked fine, Map gives you O(1) for both. So I thought I was done. Then came getRandom(). I wrote Array.from(this.map.keys()) to pick a random element. It worked. Tests passed locally. But it was O(n), rebuilding an entire array from the map on every single call. The problem explicitly requires O(1) for all three operations. My solution was silently failing the constraint. I also had a crash hiding in insert. I wrote this.map.insert(val), but JavaScript's Map has no insert() method. The correct method is .set(). One wrong method name and the whole class throws a TypeError at runtime. The real fix wasn't patching getRandom(). It was rethinking the data structure entirely. The trick: maintain both a Map and an Array together. The Array holds the actual values so getRandom() is just a random index lookup, pure O(1). The Map stores each value's index in the array so insert and remove stay O(1) too. The hardest part? Remove. You can't just delete from the middle of an array in O(1). The solution: swap the target element with the last element, pop the end, then update the swapped element's index in the Map. No shifting, no gaps. Two bugs in one problem. One crashed the code, one passed tests but broke the core constraint. The real lesson? Passing test cases is not the same as meeting complexity requirements. Always verify your Big O, not just your output. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
LeetCode Day 20 : Problem 15 (3Sum) Just solved my LeetCode problem for today. It was "3Sum", find all unique triplets in an array that add up to zero. Sounds like a natural extension of Two Sum, right? Just add a third pointer. But here's what I actually learned: The naive extension doesn't work cleanly. Three nested loops give you O(n³) and you still have to deduplicate the output, which becomes its own problem. The real insight is that sorting first unlocks everything else. Once the array is sorted, you fix one number with an outer loop and reduce the remaining problem to exactly Two Sum II on the rest of the array. Two pointers, moving inward, same logic as yesterday. O(n²) total, one pass per fixed element. But the deduplication is where this problem actually lives. There are three places duplicates can sneak in and each needs its own guard. The first is the outer pointer. If nums[i] equals nums[i-1], you've already explored every triplet that starts with this value. Skip it. The second and third are the inner pointers after finding a valid triplet. If nums[left] equals nums[left+1], moving left forward once would just find the same triplet again. Same for the right side. So you skip past all consecutive duplicates before moving both pointers inward. The order of those inner skips matters too. You skip duplicates first, then move the pointers. Not the other way around. Sorting is doing most of the heavy lifting here. It makes the two-pointer approach possible, it makes duplicate detection trivial with a single comparison, and it guarantees that once your fixed element is positive, no valid triplet can exist ahead of it since two positives can never sum to zero with another positive. The real lesson? Sorting is often the unlock that turns an ugly O(n³) problem into a clean O(n²) one. Before writing nested loops, ask whether sorting the input first changes what's possible. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
Explore related topics
- Coding Best Practices to Reduce Developer Mistakes
- Code Planning Tips for Entry-Level Developers
- Preventing Bad Coding Practices in Teams
- Simple Ways To Improve Code Quality
- Ways to Improve Coding Logic for Free
- Clean Code Practices For Data Science Projects
- Keeping Code DRY: Don't Repeat Yourself
- Early Return Techniques for Cleaner Code Structure
- Best Practices for Writing Clean Code
- How to Improve Code Maintainability and Avoid Spaghetti Code
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