Day 01: Precision Matters 🔢 Kicking off my coding journey by tackling a classic: The Plus Minus Challenge. The Problem: Given an array of integers, calculate the ratios of positive numbers, negative numbers, and zeros. The catch? The output must be precise to six decimal places. The Solution: It’s all about iteration and formatting. By looping through the array and categorizing each element, we can determine the counts. The key to meeting the precision requirement in JavaScript is using the .toFixed(6) method. javascript function plusMinus(arr) { let n = arr.length; let positive = 0, negative = 0, zero = 0; for(let val of arr) { if(val > 0) positive++; else if(val < 0) negative++; else zero++; } console.log((positive/n).toFixed(6)); console.log((negative/n).toFixed(6)); console.log((zero/n).toFixed(6)); } plusMinus(arr); Key Takeaway: Even simple logic requires attention to detail—especially when it comes to floating-point precision! #CodingChallenge #JavaScript #ProblemSolving #100DaysOfCode #DataStructures
Precision Matters in JavaScript Plus Minus Challenge
More Relevant Posts
-
hi connections Day 22 of 30: Extending the Prototype with LeetCode 2619 🚀 Today’s challenge, Array Prototype Last, dives into one of JavaScript’s most powerful features: Prototypal Inheritance. Instead of writing a standard function, the task was to enhance the global Array object so that every array can call .last() to retrieve its final element. The Logic By adding a method to Array.prototype, we make it available to every array instance. Inside the function, the this keyword refers to the array itself, allowing us to access its length and indices. Key Takeaways: The "this" Context: Understanding how this refers to the calling object is crucial for building custom utilities. Edge Case Handling: In this problem, returning -1 for empty arrays is a specific requirement that differs from the usual undefined. Efficiency: Accessing an element by index is O(1), making this a lightning-fast operation regardless of array size. Customizing prototypes is a common practice in library development, and mastering it helps in writing cleaner, more intuitive code for complex applications. One more day down, more logic mastered! 💻✨ #JavaScript #LeetCode
To view or add a comment, sign in
-
-
📘 Big O Notation I’ve been spending some time understanding Big O Notation — it felt confusing at first, but it’s becoming clearer little by little. Big O is a way to understand how efficient our code is as the input size grows. It’s not about exact speed, but about how well an algorithm scales. 💡What I practiced: • Learned the basics like O(1), O(log n), O(n), and O(n²) • Compared how arrays and sets behave in different operations • Used simple loops, map, and forEach to see how performance changes • Wrote small examples to better understand the differences 🧠 My takeaway: Just because code works doesn’t mean it’s efficient. Thinking about performance from the beginning really matters. Still learning, but getting more comfortable with these concepts. #BigONotation #TimeComplexity #CodingJourney #JavaScript #LearningEveryday
To view or add a comment, sign in
-
-
I've read the definition of closures probably 10 times. "A function bundled with its lexical scope." Made sense on paper. But I never truly got it until I came across the backpack analogy. Here's how it actually works: When a function is returned from a higher order function, it doesn't leave empty handed. It carries a backpack. That backpack is attached via a hidden [[scope]] link and contains persistent memory of the variables from its outer environment, even after that outer function has finished executing. The data lives on. Attached to the function. Quietly. And once I understood that, everything clicked: → once() runs a function exactly one time, then remembers it already ran → memoize() caches previous results so you never compute the same thing twice → iterators maintain position in a sequence across multiple calls → module pattern keeps variables private, exposes only what you choose → async programming lets callbacks remember the context they were created in All of these are closures in action. I've been writing JavaScript for 3 years. Going back to the fundamentals has been humbling and genuinely eye opening. If you've been skimming over closures, I'd recommend diving deep. It changes how you read code. #javascript #webdevelopment #softwareengineering #frontenddevelopment #continuouslearning
To view or add a comment, sign in
-
-
🤔 Ever wondered… Why this works: console.log(a) // undefined var a = 10; But this crashes: console.log(b) // ReferenceError let b = 20; Even though both are declared later? 👉 This is where most developers think they understand JavaScript… but they don’t. 🚀 Let’s break it down: Hoisting & Temporal Dead Zone (TDZ) 🧠 Hoisting (What actually happens behind the scenes) JavaScript doesn’t execute your code line by line directly. Before execution, it runs a Memory Creation Phase where: • Variables & functions are registered in memory • Declarations are processed first 👉 This is what we call hoisting 📦 Variable Hoisting With var: • Declaration is hoisted • Initialized with undefined So: • You can access it before declaration • But you won’t get the actual value , since Initialized with undefined in memory creation phase 💡 Key insight: Hoisting ≠ moving code It’s about how memory is allocated internally. ⚠️ let & const → Temporal Dead Zone (TDZ) Yes — let and const are also hoisted. But… They stay in a Temporal Dead Zone from: 👉 start of scope → until declaration line Accessing them early = 💥 ReferenceError 💡 Takeaway: TDZ exists to prevent unpredictable bugs caused by premature access. 👑 Function Hoisting (VIP behavior) Function Declarations are fully hoisted: ✔ You can call them before declaration But Function Expressions behave differently: • var → undefined • let/const → ReferenceError ⚡ Why this actually matters (not just theory) Understanding hoisting + TDZ helps you: • Avoid silent bugs (undefined issues) • Write predictable, cleaner code • Debug scope-related issues faster • Truly understand how JS engine works 💡 Final Thought: Most developers memorize hoisting. Good developers understand execution context. Great developers write code that doesn’t depend on hoisting at all. 📌 I’ll be sharing more deep dives like this as I learn & build in public. Follow along if you’re into JavaScript internals 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #Hoisting #TDZ #LearnJavaScript #CodingTips #BuildInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
Can you pass parameters in a function call like this — (1)(2)(3)? In a normal function, we pass multiple arguments at once: functionName(1, 2, 3); But how can we pass parameters in separate parentheses? That concept is called currying. In a normal function, we accept multiple arguments and perform an operation. For example: function multiply(a, b, c) { return a * b * c; } multiply(1, 2, 3); // 6 Here, we must pass all arguments together. Otherwise, the function won’t work as expected. In currying, we break this into multiple functions, where each function takes only one argument: const multiply = a => b => c => a * b * c; multiply(1)(2)(3); // 6 Each function returns another function until all arguments are received. The real advantage of currying is reusability and flexibility: const double = multiply(2); double(3)(4); // 24 Here, we reuse part of the function by fixing one argument. So, currying is not about reducing code — it’s about creating more flexible and reusable functions when needed. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #Currying #FunctionalProgramming #Closures #JavaScriptConcepts #JSBasics
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
-
-
Last night, I was debugging an API flow that should have taken 5 minutes… but it didn’t 😅 The code looked like this: .then().then().then().catch() And somewhere in that chain, things broke. Finding it? Painful. ⚠️ Problem Promise chains are powerful, but as they grow: • Hard to read 👀 • Error handling gets messy • Debugging feels like chasing shadows 💡 Solution / Insight I rewrote it using async/await: Replace .then() with await Wrap logic in try/catch Keep flow top-to-bottom Now it reads like normal code ✨ And performance? 👉 Almost identical. Both use Promises under the hood. 🧠 Takeaway It’s not about speed… it’s about clarity. Cleaner code = fewer bugs = faster dev 🚀 I share more simple dev insights here 👉 webdevlab.org 💬 Your turn Do you prefer Promise chains or async/await for real-world projects? #javascript #webdevelopment #asyncawait #programming #softwareengineering
To view or add a comment, sign in
-
-
I spent HOURS debugging… and the bug was just ONE line. 😅 Everything looked fine. No syntax errors. No warnings. But the output? Completely wrong. console.log([] == false); // true console.log([] === false); // false Wait… what? 🤯 How can the same values give different results? Then it hit me — one of JavaScript’s most confusing concepts: 👉 Type Coercion Here’s what’s happening behind the scenes: "[] == false" ➡ JavaScript converts both values ➡ becomes "0 == 0" ➡ ✅ true "[] === false" ➡ Strict comparison (no conversion) ➡ ❌ false Same values. Different rules. Completely different results. ⚠️ This is where many bugs are born — not because we don’t know JavaScript… but because JavaScript behaves unexpectedly. 💡 Lesson (relearned the hard way): Always prefer "===" over "==" ✔ "===" → checks value + type ❌ "==" → tries to be “smart” (and gets risky) Sometimes debugging isn’t about writing more code… it’s about understanding how the language actually works. Have you ever faced a bug that made you question everything? 👇 #JavaScript #Debugging #WebDevelopment #Programming #Developers #Coding #SoftwareEngineering #LearnToCode #TechLife
To view or add a comment, sign in
-
-
new blog. 📝 Destructuring in JavaScript cleaner code. less repetition. more readable. destructuring is one of those features you don't know you needed until you use it once then you can't stop. link: https://lnkd.in/gNgvuG-4 Hitesh Choudhary Piyush Garg Akash Kadlag Jay Kadlag
To view or add a comment, sign in
-
-
Ever felt like your functions could be more flexible and reusable? 🤔 That’s where currying in JavaScript comes in! Instead of passing all arguments at once, currying transforms a function into a sequence of functions — each taking a single argument. ✨ Why it matters: • Improves code reusability • Encourages cleaner, modular design • Makes function composition easier 🔍 Example: const add = a => b => a + b; Now you can do: const add5 = add(5); add5(3); // 8 Small change, big impact 💡 If you're diving deeper into functional programming, currying is definitely a concept worth mastering. #JavaScript #WebDevelopment #FunctionalProgramming #CleanCode #100DaysOfCode
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