🚀 Day 8 / 30 - JavaScript Coding Practice Today’s challenge: Rebuilding Array.filter() without using the built-in method 👀 Problem: Given an integer array arr and a filtering function fn, return a filtered array filteredArr. The fn function takes one or two arguments: arr[i] - number from the arr i - index of arr[i] filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true. Please solve it without the built-in Array.filter method. Example 1: Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; } Output: [20,30] Explanation: const newArray = filter(arr, fn); // [20, 30] The function filters out values that are not greater than 10 Example 2: Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; } Output: [1] Explanation: fn can also accept the index of each element In this case, the function removes elements not at index 0 Example 3: Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 } Output: [-2,0,1,2] Explanation: Falsey values such as 0 should be filtered out Solution: var filter = function (arr, fn) { let formattedArr = []; for (let i = 0; i < arr.length; i++) { if (fn(arr[i], i)) { formattedArr.push(arr[i]); } } return formattedArr; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment #ProblemSolving
Rebuilding Array.filter() in JavaScript
More Relevant Posts
-
If you’ve been working with JavaScript, you’ve likely encountered deeply nested callbacks that make code difficult to read and maintain — commonly known as Callback Hell. This pattern not only reduces code readability but also increases the chances of bugs and poor error handling. In this article, I’ve explained: ✔ What Callback Hell is ✔ Why it happens ✔ Real-world examples ✔ How to avoid it using Promises and async/await Whether you're a beginner or improving your coding practices, understanding this concept is essential for writing clean and scalable JavaScript. 📖 Read here: https://lnkd.in/gNaAjDkk Let me know your thoughts or how you handle asynchronous code 👇 #JavaScript #SoftwareDevelopment #WebDevelopment #AsyncProgramming #CodingBestPractices #Developers
To view or add a comment, sign in
-
In JavaScript, errors are not rare edge cases. They are part of normal execution. The difference between fragile and reliable code is how you handle them. In my latest blog, I break down: • What runtime errors actually are (and why they matter) • How try and catch really work under the hood • The role of the finally block • How to throw and design custom errors • Why graceful failure is a core engineering skill https://lnkd.in/gkYpAYfX #JavaScript #WebDevelopment #FrontendDevelopment #Programming #SoftwareEngineering #Coding #LearnToCode #Developers #ErrorHandling
To view or add a comment, sign in
-
Day 11 / 30 - Javascript Coding Challenge - Memoization in JavaScript 🚀 Problem: Given a function fn, return a memoized version of that function. A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. You can assume there are 3 possible input functions: sum, fib, and factorial. sum accepts two integers a and b and returns a + b. Assume that if a value has already been cached for the arguments (b, a) where a != b, it cannot be used for the arguments (a, b). For example, if the arguments are (3, 2) and (2, 3), two separate calls should be made. fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise. factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise. Solution: function memoize(fn) { let memoValues = {}; return function (...args) { const key = JSON.stringify(args) if (key in memoValues) { return memoValues[key]; } else { memoValues[key] = fn(...args); return memoValues[key]; } }; } #JavaScript #Memoization #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
Most developers think inheritance in JavaScript works like traditional OOP. It doesn’t. And that confusion leads to messy, over-engineered code. JavaScript uses prototypal inheritance — not classical inheritance. 👉 Objects inherit directly from other objects. 💡 There are 3 main ways inheritance works in JavaScript: 🔹 1. Prototypal Inheritance (Core Concept) const animal = { speak() { console.log("Makes a sound"); } }; const dog = Object.create(animal); dog.bark = function () { console.log("Bark"); }; dog.speak(); // inherited dog.bark(); // own method ✔ Simple ✔ Flexible ✔ Native to JS 🔹 2. Constructor Function Inheritance function Animal(name) { this.name = name; } Animal.prototype.speak = function () { console.log(this.name + " makes noise"); }; function Dog(name) { Animal.call(this, name); // inherit properties } Dog.prototype = Object.create(Animal.prototype); const d = new Dog("Tommy"); d.speak(); ✔ More structured ✔ Used in older codebases 🔹 3. Class-based Inheritance (ES6) class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + " makes noise"); } } class Dog extends Animal { bark() { console.log("Bark"); } } const dog = new Dog("Rocky"); dog.speak(); dog.bark(); ✔ Cleaner syntax ✔ Easier to read ❗ Still uses prototypes under the hood ⚡ The truth most people miss: Even with classes… 👉 JavaScript is STILL prototype-based. Classes are just syntactic sugar. 🧠 The real upgrade: Stop thinking: “Which syntax should I use?” Start thinking: “How does inheritance actually work under the hood?” Because once you understand prototypes… You don’t just write code— you understand it. What confused you more in JavaScript—closures, promises, or prototypes? 👇 #JavaScript #WebDevelopment #Programming #Frontend #Coding #SoftwareEngineering
To view or add a comment, sign in
-
Async/Await is one of the most powerful features in JavaScript — but it’s also easy to misuse. Over time, I’ve seen developers (including myself) make common mistakes like: • Not handling errors properly with try/catch • Using await unnecessarily and slowing down performance • Forgetting to run promises in parallel with Promise.all() • Mixing async patterns in a confusing way These issues may look small, but they can impact performance and code reliability in real-world applications. So I wrote a detailed article breaking down the most common async/await mistakes with clear examples and practical explanations. If you're working with JavaScript, this will definitely help you write cleaner and more efficient code. 👉 Read here: https://lnkd.in/gxheFKiN I’d love to hear — what’s the biggest async/await mistake you’ve encountered? #JavaScript #AsyncAwait #SoftwareDevelopment #WebDevelopment #Programming #CodeQuality
To view or add a comment, sign in
-
Wrote a new blog on Destructuring in JavaScript. One of those features that seems small at first, but has a huge impact on code quality. Covering: • What destructuring actually means • Array vs object destructuring • Default values (and why they matter) • Before vs after comparisons • Writing cleaner, more readable code https://lnkd.in/g2y6rmnt Hitesh Choudhary Chai Aur Code Piyush Garg Akash Kadlag Jay Kadlag Nikhil Rathore #javascript #webdevelopment #frontend #coding #programming #developers #learninpublic #100daysofcode
To view or add a comment, sign in
-
Most JavaScript bugs don’t come from syntax… They come from 𝐦𝐢𝐬𝐮𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐬𝐜𝐨𝐩𝐞. Why does `var` behave differently from `let`? Why do closures “remember” variables? Why do some variables leak into global scope? If these questions have ever confused you, this is worth reading. Read here: https://lnkd.in/gybfSz6F #JavaScript #Coding #SoftwareEngineering
To view or add a comment, sign in
-
Handling errors properly is one of the most underrated skills in JavaScript development. Many developers use try...catch, but not everyone understands: ✔ When to use it ✔ How it works internally ✔ Common mistakes to avoid I’ve created a detailed yet beginner-friendly article on: 👉 How to handle Errors with try/catch in JavaScript It includes: • Simple explanations • Real-world examples • Practical use cases • Common pitfalls If you're aiming to write more stable and professional JavaScript code, this will be helpful. 🔗 Read here: https://lnkd.in/gXMTtyxd I’d love to hear your thoughts or questions in the comments! #JavaScript #ErrorHandling #WebDevelopment #Frontend #Programming #SoftwareDevelopment #Coding
To view or add a comment, sign in
-
🧠 JavaScript Myth Busting: "Let and Const are not Hoisted" (Yes, they are!) Have you ever been told in an interview that "let" and "const" aren’t hoisted, but "var" is? It’s one of the most common misconceptions in JavaScript. 👉 Here is the 100% technical truth: All declarations in JavaScript ("var", "let", "const", "function", "class") are hoisted. So, why do they behave differently? It’s all about Initialization and a friendly little neighborhood called the Temporal Dead Zone (TDZ). --- 🚨 The Difference: 1️⃣ "var" is hoisted AND initialized immediately with the value of "undefined". You can access it before its line of code without crashing. 2️⃣ "let" and "const" are hoisted BUT NOT initialized. The JavaScript engine knows they exist, but it reserves the memory without setting any starting value. --- 💀 Enter the Temporal Dead Zone (TDZ): The TDZ is the period of time between the start of a block and the moment the variable is actually initialized (the line where you wrote the declaration in your code). If you try to touch a "let" or "const" variable while it is trapped in the TDZ, JavaScript throws a ReferenceError. --- 💡 Why does this matter? The TDZ exists to enforce better coding practices. It helps prevent bugs by stopping you from using variables that have been created but aren't yet ready for use. --- 📌 Check out the image below for a simple breakdown! 👇 💬 Drop your best analogies in the comments! #javascript #coding #webdevelopment #programmingmyths #softwareengineering #learncoding #frontend
To view or add a comment, sign in
-
-
Understanding the Event Loop in JavaScript is a turning point for every developer. Many developers use async features like promises, setTimeout, or async/await daily — but very few truly understand what happens behind the scenes. I’ve written a detailed yet easy-to-understand article that breaks down: ✔ Call Stack ✔ Callback Queue ✔ Microtask Queue ✔ Execution Order If you want to strengthen your JavaScript fundamentals and avoid common async mistakes, this will definitely help. 👉 Read the full article: https://lnkd.in/gDhwvmUc I’d love to hear your thoughts — what was the hardest concept for you when learning the Event Loop? #JavaScript #SoftwareDevelopment #WebDevelopment #FrontendDevelopment #AsyncProgramming #Coding #TechLearning
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