Day 6 — Find Second Largest Number in an Array (JavaScript) Problem Write a function to find the second largest number in an array. Example Input: [10, 5, 8, 20] Output: 10 Approach First find the largest number, then find the largest number smaller than it. Code function secondLargest(arr){ let largest = -Infinity let second = -Infinity for(let i = 0; i < arr.length; i++){ if(arr[i] > largest){ second = largest largest = arr[i] } else if(arr[i] > second && arr[i] !== largest){ second = arr[i] } } return second } console.log(secondLargest([10,5,8,20])) Alternative Approach function secondLargest(arr){ let sorted = [...new Set(arr)].sort((a,b) => b-a) return sorted[1] } What I Learned How to track two maximum values in a single loop. #javascript #frontenddeveloper #codingpractice #webdevelopment
Kajal Yadav’s Post
More Relevant Posts
-
Day 5 — Find Largest Number in an Array (JavaScript) Problem Write a function to find the largest number in an array. Example Input: [3, 7, 2, 9, 5] Output: 9 Approach Loop through the array and keep track of the maximum value. Code function findLargest(arr){ let max = arr[0] for(let i = 1; i < arr.length; i++){ if(arr[i] > max){ max = arr[i] } } return max } console.log(findLargest([3,7,2,9,5])) Alternative Approach function findLargest(arr){ return Math.max(...arr) } What I Learned How to track maximum value while iterating through an array. #javascript #frontenddeveloper #codingpractice #webdevelopment
To view or add a comment, sign in
-
-
🔥 Stale Closure in React — A Common Bug You Must Know Ever faced a situation where your state is not updating correctly inside setTimeout / setInterval / useEffect? 🤯 👉 That’s called a Stale Closure --- 💡 What is happening? A function captures the old value of state and keeps using it even after updates. --- ❌ Example (Buggy Code): import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { setInterval(() => { console.log(count); // ❌ Always logs 0 (stale value) }, 1000); }, []); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } 👉 Why? Because the closure captured "count = 0" when the effect first ran. --- ✅ Fix (Correct Approach): useEffect(() => { const id = setInterval(() => { setCount(prev => prev + 1); // ✅ always latest value }, 1000); return () => clearInterval(id); }, []); --- 🎯 Key Takeaway: Closures + async code (setTimeout, setInterval, event listeners) = ⚠️ potential stale state bugs --- 💬 Interview One-liner: “Stale closure happens when a function uses outdated state due to how closures capture variables.” --- 🚀 Mastering this concept = fewer bugs + stronger React fundamentals #ReactJS #JavaScript #Frontend #InterviewPrep #Closures #WebDevelopment
To view or add a comment, sign in
-
JavaScript Closures are confusing… until they’re not ⚡ Most developers memorize the definition but struggle to actually understand it. Let’s simplify it 👇 💡 What is a closure? A closure is when a function 👉 remembers variables from its outer scope even after that scope is finished 🧠 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 fn(); // 3 ⚡ Why this works: inner() still has access to count even after outer() has executed 🔥 Where closures are used: • Data hiding • State management • Event handlers • Custom hooks in React #JavaScript #FrontendDeveloper #ReactJS #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Stop guessing the order of your console.logs. 🛑 JavaScript is single-threaded. It has one brain and two hands. So, how does it handle a heavy API call, a 5-second timer, and a button click all at once without catching fire? It’s all about the Event Loop, but specifically, the "VIP treatment" happening behind the scenes. The Two Queues You Need to Know: 1. The Microtask Queue (The VIP Line) 💎 What lives here: Promises (.then), await, and MutationObserver. The Rule: The Event Loop is obsessed with this line. It will not move on to anything else until this queue is bone-dry. If a Promise creates another Promise, JS stays here until they are all done. 2. The Macrotask Queue (The Regular Line) 🎟️ What lives here: setTimeout, setInterval, and I/O tasks. The Rule: These tasks are patient. The Event Loop only picks one at a time, then goes back to check if any new VIPs (Microtasks) have arrived. The "Aha!" Moment Interview Question: What is the output of this code? (Most junior devs get this wrong). JavaScript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); The Reality: 1. Start (Sync) 2. End (Sync) 3. Promise (Microtask - Jumps the line!) 4. Timeout (Macrotask - Even at 0ms, it waits for the VIPs) The Pro-Tip for Performance 💡 If you have a heavy calculation, don't wrap it in a Promise thinking it makes it "background." It’s still on the main thread! Use Web Workers if you really want to offload the heavy lifting. Does the Event Loop still confuse you, or did this click? Let's discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🧠 React Doesn’t Update State Immediately (Even Inside the Same Function) Most people know state is async. But here’s the part many don’t realize 👇 Example const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); if (count === 0) { console.log("Still zero?"); } } You click the button. Expected: count = 1 But inside that function… 👉 count is still 0 🔍 Why? Because React doesn’t update state inside the current render cycle. It schedules the update and re-renders later. 🧠 The tricky part Even this won’t work: setCount(count + 1); setCount(count + 1); 👉 Final result = +1, not +2 ✅ Correct way setCount(prev => prev + 1); setCount(prev => prev + 1); Now React uses the latest value. 🎯 The Real Insight State inside a function is a snapshot, not a live value. 💥 Why this matters This causes: Unexpected conditions Wrong calculations Confusing bugs #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #CodingTips #LearningInPublic
To view or add a comment, sign in
-
Most JS developers use closures daily without knowing it. counter() finished running, but increment still remembers count. That's a closure. How does it remember? When a function is created in JavaScript, it doesn't just save the code — it also saves a reference to the variables around it at that moment. So even after the outer function is gone, that reference stays alive in memory as long as the inner function exists. Think of it like this the inner function carries a backpack of its outer variables wherever it goes. 🎒 You already use this in React's useState, debounce, and event handlers. Once I understood this, my React bugs started making sense. 🙂 Did closures confuse you at first? Drop a comment 👇 #JavaScript #MERN #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Most devs reach for a state management library too fast. Before you install Redux or Zustand, try this 👇🏾 // Manage related state together, not separately const [form, setForm] = useState({ name: '', email: '', password: '' }) const handleChange = (e) => { setForm(prev => ({ ...prev, [e.target.name]: e.target.value })) } One state object. One handler. Works for 90% of forms. Stop adding dependencies before you need them. Save this 🔖 #ReactJS #JavaScript #WebDevelopment #Fullstack #CodingTips
To view or add a comment, sign in
-
-
Most React developers know this rule: “Don’t call hooks inside loops or conditions.” But far fewer understand why. React doesn’t track hooks by variable name or location. It tracks them purely by call order during render. So internally, it’s closer to this mental model: • First useState → slot 0 • Second useState → slot 1 • Third useState → slot 2 Each hook call is mapped based on its position in the sequence. Now imagine this: if (isLoggedIn) { useState(...) } On one render the hook is called, on another it’s not. That shifts the entire sequence. React will still read: • “2nd hook → slot 1” But now it’s actually reading the wrong state. I built a minimal useState implementation (attached) to demonstrate this. You’ll notice: • Hooks are stored in an array • Each call consumes the next index • The index resets on every render • Everything depends on consistent ordering That’s the real rule: It’s not about avoiding conditions It’s about keeping hook calls in the same order every render Once that order changes, state association breaks. #React #JavaScript #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
Worked on a few small projects while learning JavaScript in the browser. Focused mainly on: • DOM manipulation • forms and validation • timers (setTimeout, setInterval) • localStorage Nothing complex, but enough to understand how things actually behave. Handling user input, updating the UI, storing data - all of it made JavaScript feel more practical. These small projects helped connect multiple concepts together instead of learning them in isolation. #javascript #webdevelopment #frontend
To view or add a comment, sign in
-
𝗪𝗵𝘆 𝗬𝗼𝘂 𝗦𝗵𝗼𝘂𝗹𝗱 𝗦𝘁𝗼𝗽 𝗠𝘂𝘁𝗮𝘁𝗶𝗻𝗴 𝗔𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 (𝘚𝘦𝘳𝘪𝘰𝘶𝘴𝘭𝘺) 🧐 If you’ve been writing JavaScript for a while, you’ve probably spent hours debugging a feature that simply refused to update on the screen, only to realize the data had changed, but the app didn’t know it. #javascript #WebDevelopment #FullStackDeveloper
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
Use Number.MAX_VALUE and Number.MIN_VALUE