For years, finding the last matching element or its index in a JavaScript array meant writing clumsy loops or reversing arrays. This not only added unnecessary lines of code but also obscured the intent, making your code harder to read and maintain. Many developers still resort to these manual iterations because they're familiar patterns or they're simply unaware of the newer, more direct Array methods. Using verbose loops for a common task like finding the last occurrence can introduce subtle bugs, especially when managing loop conditions and break statements. The lack of a native `findLast()` or `findLastIndex()` method led to developers crafting custom solutions that varied in performance and reliability across codebases. This inconsistency made onboarding new team members tougher and slowed down code reviews. It also forced developers to write more complex conditional logic to handle edge cases like empty arrays or no matches. With `Array.findLast()` and `Array.findLastIndex()`, introduced in ES2023, you can achieve this with a single, expressive line of code. These methods are concise, performant, and make your code's purpose immediately clear. Are you still using reverse loops or `reduceRight()` to find the last matching item? #JavaScript #ES2023 #WebDevelopment #CodeCleanUp #JSArrayMethods
Find Last Element in JavaScript Array with ES2023 Methods
More Relevant Posts
-
JavaScript's Date object was broken in 1995. It took 31 years to fix it. ES2026 finally did it. 🎉 The Temporal API is here — and it's just the start of what ES2026 ships. Here's every feature that changes how you write JS: 🗓️ Temporal API — immutable, timezone-aware dates. Drop Moment.js for good. 🔒 using + await using — automatic resource cleanup. No more forgotten try/finally blocks. Files, DB connections, streams — all closed automatically when scope exits. ➕ Math.sumPrecise() — floating point math that actually works. [1e20, 0.1, -1e20].reduce((a,b)=>a+b) = 0 ❌ Math.sumPrecise([1e20, 0.1, -1e20]) = 0.1 ✅ ✅ Error.isError() — reliable error detection across iframes and VM contexts. instanceof Error was never trustworthy. ⚡ Array.fromAsync() — collect async iterables in one line. The async equivalent of Array.from. 🗺️ Map.getOrInsert() — upsert without the boilerplate. No more has() → set() → get() chains. 🔢 Uint8Array Base64/Hex methods — built-in binary encoding. No more btoa() gymnastics. 🔗 Iterator.concat() — chain iterators lazily. No intermediate arrays. I broke down every feature with before/after code in my article. Which feature are you most excited about? Drop a comment 👇 #JavaScript #ES2026 #ECMAScript #WebDev #Frontend #Programming #100DaysOfBlogging
To view or add a comment, sign in
-
What To Know in JavaScript (2026 Edition). Part 1. Iterator Helpers (lazy data processing) JavaScript introduced Iterator Helpers — methods like .map(), .filter(), .take() directly on iterators. The goal is to avoid unnecessary intermediate arrays and improve performance. Instead of chaining operations that create arrays at every step, you get: → less memory usage → fewer computations → more predictable performance #frontend #webdev #javascript #performance
To view or add a comment, sign in
-
-
Day 12/100 of JavaScript 🚀 Today’s topic: async / await "async" and "await" provide a cleaner way to work with Promises and write asynchronous code that looks like synchronous code 📍Basic example async function getData() { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } 📍With error handling async function getData() { try { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 🔑 Key points : - "async" makes a function return a Promise. - "await" pauses execution until the Promise resolves. - Makes code more readable than ".then()" chaining. async/await simplifies handling asynchronous operations while still using Promises under the hood. #Day12 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
Day 10/100 of JavaScript 🚀 Today’s topic : Fetch API "fetch" is used to make HTTP requests in JavaScript and is a modern replacement for XMLHttpRequest Basic usage : fetch("https://lnkd.in/gCA7VyNQ") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); Using async/await : async function getData() { try { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } What it does : - Returns a Promise - Cleaner than XMLHttpRequest - Works well with async/await #Day10 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
🚀 From Arrays to Efficiency: Mastering Set in JavaScript Today I solved the “Unique Rows in Boolean Matrix” problem using one simple yet powerful concept — Set. At first glance, the problem looks like a typical nested loop challenge. But instead of going brute force, I leveraged Set to achieve a clean and optimal solution. 💡 Key Idea: Convert each row into a string and store it in a Set to automatically handle duplicates. ✨ Why this is powerful: Eliminates duplicates in O(1) lookup time Avoids unnecessary nested loops Keeps the solution clean and readable 📊 Complexity: Time: O(n × m) Space: O(n × m) 🔥 Takeaway: Sometimes, the difference between an average solution and an optimal one is just knowing the right data structure. Today it was Set. Tomorrow, it could be something else. 💬 Curious: Where else have you used Set to simplify a problem? #JavaScript #DSA #CodingInterview #WebDevelopment #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝗻 𝟮𝟬𝟮𝟲 JavaScript changed. Tools are better now. You still fall into old traps. Avoid these 5 mistakes. - Top-level await It is risky in libraries. It creates race conditions. Use a singleton pattern. This protects your bundle size. - The == operator Stop using ==. It uses confusing logic. It ruins type safety. Use === for all checks. - let in async loops let is block-scoped. Async loops capture live values. Your logs will show the same number. Use a const inside the loop. - The this keyword Arrow functions do not bind this. They use the outer scope. This leads to undefined. Use regular functions for methods. - JSON and Dates JSON.parse returns strings. It does not create Date objects. Your code will crash. Use a reviver function. Source: https://lnkd.in/g4yDDjNe
To view or add a comment, sign in
-
I built a JS Minifier that does more than just remove whitespace. 🛠️⚡ Most online minifiers are "black boxes." You paste code, and you get a mess back. I wanted to build something that helps developers understand how their code is being transformed. The Engineering Details: AST Debugging : Built-in visualization using acorn to inspect the Abstract Syntax Tree. Zero UI Lag : Minification runs in a Web Worker, keeping the main thread free for a 60fps experience. Modern Compatibility: Fully supports ES2024+ syntax, powered by Terser. Smart State: Persistent configuration via localStorage and a responsive UI using react-resizable-panels. Mangle & Compress: Smart variable renaming and dead-code removal. The Results: In my tests, I'm consistently seeing 40-60% size reductions in milliseconds. #JavaScript #WebDev #Performance #Frontend #VibeCoding
To view or add a comment, sign in
-
-
If a function fires 1000 times, but you only want it to run every 100 calls, there's a neat technique for that. Today I learned about counter-based sampling in JavaScript. Use Cases • sampling analytics events to reduce load • limiting noisy logs or metrics • running expensive work periodically in high-frequency flows How it's different from throttling? Sampling is call-count based → run every N calls Throttling is time-based → run at most once every X ms So if 1000 events fire instantly: • sampling (every 100) → runs 10 times • throttling (200ms) → may run only once Different problems, different tools. #javascript #softwareengineering #frontend #webdevelopment #todayilearned
To view or add a comment, sign in
-
-
There's always something to gain from going back to the fundamentals. Between client projects and building out systems, I've been carving out time to sharpen my JavaScript. Recently covered: → Primitive vs Reference Data Types → Number, Null, Undefined, BigInt, and Symbols → The typeof operator → Ternary operators → Introduction to Object Destructuring None of this is glamorous. But the designers and developers who write clean, predictable code are almost always the ones who took the fundamentals seriously. Still a few more concepts on the list. Sharing the progress as I go. #JavaScript #WebDevelopment #Webflow #LearningInPublic
To view or add a comment, sign in
-
-
Today I finally understood how JavaScript actually stores data in memory — and it changed the way I look at code. Earlier, I used to just write variables and functions without thinking much about what’s happening behind the scenes. But now it makes a lot more sense: Primitive values (like numbers, strings, booleans) are stored directly in memory Reference types (like arrays and objects) are stored differently — the variable holds a reference, not the actual value That’s why things like this behave unexpectedly sometimes: Copying objects doesn’t create a real copy Changing one reference can affect another Understanding this cleared up a lot of confusion I had while debugging. Still learning, but this felt like a small breakthrough Hitesh Choudhary Piyush Garg Chai Code #JavaScript #WebDevelopment #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
Explore related topics
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