🚀 Recursion in JavaScript 🔁 What is a Recursive Function? A recursive function is a function that keeps calling itself until a condition is met. 👉 Instead of using loops, it breaks a problem into smaller sub-problems and solves them step by step. ⚙️ Basic Structure Every recursive function has 2 important parts: 1. ✅ Base Case (Stopping Condition) >> Prevents infinite calls >> Tells the function when to stop 2. 🔁 Recursive Case >> Function calls itself with smaller input 📌 Example 1: Factorial function factorial(n) { if (n === 0) return 1; // base case return n * factorial(n - 1); // recursive call } console.log(factorial(5)); // 120 🧠 How it works: factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * 2 * 1 = 120 📌 Example 2: Countdown function countDown(n) { if (n === 0) { console.log("Done!"); return; } console.log(n); countDown(n - 1); } countDown(5); 👉 If you don’t write a base case, it will cause: ❌ Infinite recursion ❌ Stack overflow error 🔄 Recursion vs Loops ✔ Recursion → Clean & elegant for complex problems ✔ Loops → Better for simple iterations 💡 Where Recursion is Used >>> Tree & Graph traversal >>>File/folder structures >>>Algorithms like DFS & Backtracking >>>Problems like Fibonacci, factorial #JavaScript #Coding #ProblemSolving #Recursion #WebDevelopment
Understanding Recursive Functions in JavaScript
More Relevant Posts
-
⚡15 JavaScript Senior level questions about objects: 1) How do property descriptors work, and how do get/set interact with writable/configurable/enumerable? 2) Walk through the [[Get]] and [[Set]] algorithm (prototype chain, shadowing, strict mode) 3) What’s the difference between in, hasOwnProperty, and Object.hasOwn? When is Object.hasOwn preferable? 4) Explain Object.create(null) and when you’d use it over {}. 5) this binding in object methods, method extraction, and arrow pitfalls 6) Enumerability, reflection, and key order: for…in vs Object.keys vs Object.getOwnPropertyNames vs Reflect.ownKeys 7) Deep copy strategies: structuredClone, JSON, spread, and Object.assign 8) Freezing, sealing, and extensibility: semantics and pitfalls 9) Proxies, invariants, and why Reflect is your friend 10) Symbols and well-known symbols: make plain objects iterable & controllable 11) Class fields and private fields: what are they actually? 12) super, [[HomeObject]], and why copying methods can break super 13) JSON serialization edge cases: toJSON, replacers, and lost values 14) Property definition vs assignment: descriptors, accessors, and side effects 15) Objects vs Map/WeakMap: key types, iteration, GC, and performance #JavaScript #TechInterview
To view or add a comment, sign in
-
Most JavaScript devs think Object keys follow insertion order. And it’s caught even senior devs off guard. Create an object and add keys in this order: "b", "a", "1". const obj = {}; obj.b = 'second'; obj.a = 'third'; obj.1 = 'first'; Log Object.keys(obj). You’d expect: ['b', 'a', '1'] You get: ['1', 'b', 'a'] 🤯 The number jumped to the front, but the strings stayed in order. Same object. Same assignment logic. Completely unexpected order. This silently breaks: → API wrappers that expect keys to match a specific schema → UI components that map over objects for "alphabetical" sorting → Testing suites that compare object snapshots No error thrown. Just a data structure that "rearranges" itself. Why does this happen? It’s defined in the ECMAScript spec (OrdinaryOwnPropertyKeys). JavaScript objects don't have a single "order." They follow a strict three-tier hierarchy: 1. Integer Indices: Sorted in ascending numeric order (always first). 2. String Keys: Sorted in chronological insertion order. 3. Symbol Keys: Sorted in chronological insertion order (always last). The engine treats "1" as an integer index, so it "cuts the line" and moves to the very front, regardless of when you added it. Once you know this, you'll stop trusting Object.keys() for ordered data and start reaching for Map. 🔖 Learn more about how JS engines handle property order → https://lnkd.in/gRY6hdcM Were you aware that numbers always "cut the line" in JS objects? 1️⃣ Yes / 2️⃣ No 👇 #JavaScript #WebDev #Coding #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
🤔 Ever seen RangeError: Maximum call stack size exceeded and wondered what it actually means? It usually comes down to how the call stack works, how recursion grows it, and why every JavaScript engine has depth limits. 🧠 JavaScript interview question What is the call stack, why does recursion have depth limits, and what causes a stack overflow? ✅ Short answer The call stack is where JavaScript keeps track of active function calls. Every recursive call adds a new stack frame. If recursion goes too deep, or never stops, the stack fills up and throws a stack overflow error. 🔍 A bit more detail JavaScript runs code on a single thread and uses the call stack to manage function execution. When one function calls another, a new execution context is pushed onto the stack. When a function finishes, it is popped off and control returns to the caller. With recursion, this push process keeps happening until a base case stops it. That is why a correct base case matters so much. Without it, or with too many nested calls, you eventually hit the engine's stack limit and get: RangeError: Maximum call stack size exceeded Example with a safe base case: function factorial(n) { if (n < 0) throw new Error("Negative values are not allowed"); if (n === 0 || n === 1) return 1; // base case return n * factorial(n - 1); // recursive case } console.log(factorial(5)); // 120 This works because the recursion has a clear stopping point. Here is the kind of pattern that causes stack overflow: function endless(n) { return endless(n + 1); // no base case } ⚠️ Important clarification Infinite recursion is not the only problem. Even valid recursion can fail if the input gets deep enough, because JavaScript engines have limited stack space. That is why for very deep problems, an iterative solution is often safer than recursion. #javascript #webdevelopment #frontend #codinginterview #learninpublic
To view or add a comment, sign in
-
JavaScript prototypes clicked for me the moment I stopped thinking about copying and started thinking about linking. Here's the mental model that made it stick 👇 🔹 The core idea Every object in JavaScript has a hidden link to another object — its prototype. When you access a property, JS doesn't just look at the object itself. It walks the chain: Check the object Not found? Check its prototype Still not found? Check the prototype's prototype Keep going until null That's the prototype chain. Simple as that. 🔹 See it in action jsconst user = { name: "Aman" }; const admin = { isAdmin: true }; admin.__proto__ = user; console.log(admin.name); // "Aman" ✅ admin doesn't have name — but JS finds it one level up. 🔹 Why constructor functions use this jsfunction User(name) { this.name = name; } User.prototype.sayHi = function () { console.log(`Hi, I am ${this.name}`); }; Every User instance shares one sayHi method. Not copied — linked. That's free memory efficiency, built into the language. 🔹 Two things worth keeping straight prototype → a property on constructor functions __proto__ → the actual link on any object The modern, cleaner way to set that link: jsconst obj = Object.create(user); 🔹 Why bother understanding this? Because it shows up everywhere — class syntax, frameworks, unexpected undefined bugs, performance decisions. Prototypes aren't a quirk. They are the inheritance model. One line to remember: JS doesn't copy properties. It searches a chain of linked objects. #JavaScript #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
🚀 Day 20 – Deep vs Shallow Copy in JavaScript Ever changed a copied object… and accidentally modified the original too? 😅 Yeah, that’s the shallow copy trap. Let’s fix that today 👇 🔹 Shallow Copy Copies only the first level 👉 Nested objects still share the same reference 🔹 Deep Copy Creates a fully independent clone 👉 No shared references, no unexpected bugs 💡 Real-world example (Angular devs 👇) When working with forms, APIs, or state (NgRx), a shallow copy can silently mutate your original data — leading to hard-to-debug UI issues. ⚡ Best Ways to Deep Copy ✔️ structuredClone() (modern & recommended) ✔️ JSON.parse(JSON.stringify(obj)) (with limitations) ✔️ _.cloneDeep() (lodash) 🔥 TL;DR Shallow Copy → Shares references Deep Copy → Fully independent Prefer structuredClone() whenever possible 💬 Have you ever faced a bug because of shallow copying? Drop your experience 👇 #JavaScript #Angular #WebDevelopment #Frontend #Programming #100DaysOfCode
To view or add a comment, sign in
-
-
Have you ever felt overwhelmed by JavaScript objects? The good news is that methods like Object.keys(), Object.values(), and Object.entries() can simplify how we interact with them. Which one do you find yourself using the most? ────────────────────────────── Demystifying Object.keys(), Object.values(), and Object.entries() Unlock the power of object methods in JavaScript with these simple techniques. #javascript #es6 #programming ────────────────────────────── Key Rules • Object.keys(obj) returns an array of the object's own property names. • Object.values(obj) returns an array of the object's own property values. • Object.entries(obj) returns an array of the object's own property [key, value] pairs. 💡 Try This const person = { name: 'Alice', age: 30, city: 'Wonderland' }; console.log(Object.keys(person)); // ['name', 'age', 'city'] console.log(Object.values(person)); // ['Alice', 30, 'Wonderland'] console.log(Object.entries(person)); // [['name', 'Alice'], ['age', 30], ['city', 'Wonderland']] ❓ Quick Quiz Q: What does Object.entries() return? A: An array of [key, value] pairs from the object. 🔑 Key Takeaway Using these methods can drastically improve your code's readability and efficiency! ────────────────────────────── Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery.
To view or add a comment, sign in
-
{JS Problem Solving} Today, I solved some JavaScript problems to improve my problem-solving skills. Problems I solved=> 1. Deep Flatten Array No matter how deep the nested array is, make it completely flat flatten([1, [2, [3, [4]], 5]]) // output: [1,2,3,4,5] 2️. Debounce function Create a function that will execute with a delay if called rapidly debounce(fn, 500) Real use: search input optimization 3️. Throttle Function Run the function only once in a specified time throttle(fn, 1000) Real use: scroll event 4️. Custom Promise.all() Implement it yourself myPromiseAll([p1, p2, p3]) Output: Return the result if all are resolved 5️. LRU Cache Implement Least Recently Used cache const cache = new LRUCache(2) cache.put(1, 1) cache.get(1) Real use: browser caching 6️. Group By Function Group an array groupBy(users, "age") 7️. Deep Clone Object clone nested object (no reference) deepClone(obj) JSON.parse cannot be used 8️. Infinite Curry Function Will support unlimited chaining sum(1)(2)(3)(4)() // 10 9️. Event Emitter (Node.js style) Create a custom event system emitter.on("click", fn) emitter.emit("click") 10. Retry API Call with Limit API will retry if it fails retry(fetchData, 3) Repo link: https://lnkd.in/gXtcS9qP #problemsolver #programmer #javascriptdeveloper
To view or add a comment, sign in
-
-
🧠 Day 6 — Closures in JavaScript (Explained Simply) Closures are one of the most powerful (and frequently asked) concepts in JavaScript — and once you understand them, a lot of things start to click 🔥 --- 🔐 What is a Closure? 👉 A closure is when a function “remembers” variables from its outer scope even after that scope has finished executing. --- 🔍 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 --- 🧠 What’s happening? inner() still has access to count Even after outer() has finished execution This happens because of lexical scoping --- 🚀 Why Closures Matter ✔ Data privacy (like encapsulation) ✔ Used in callbacks & async code ✔ Foundation of React hooks (useState) ✔ Helps create reusable logic --- ⚠️ Common Pitfall for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 👉 Output: 3 3 3 ✔ Fix: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } --- 💡 One-line takeaway: 👉 “A closure remembers its outer scope even after it’s gone.” --- If you’re learning JavaScript fundamentals, closures are a must-know — they show up everywhere. #JavaScript #Closures #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🧠 Day 25 — JavaScript Destructuring (Advanced Use Cases) Destructuring isn’t just syntax sugar — it can make your code cleaner and more powerful 🚀 --- 🔍 What is Destructuring? 👉 Extract values from arrays/objects into variables --- ⚡ 1. Object Destructuring const user = { name: "John", age: 25 }; const { name, age } = user; --- ⚡ 2. Rename Variables const { name: userName } = user; console.log(userName); // John --- ⚡ 3. Default Values const { city = "Delhi" } = user; --- ⚡ 4. Nested Destructuring const user = { profile: { name: "John" } }; const { profile: { name } } = user; --- ⚡ 5. Array Destructuring const arr = [1, 2, 3]; const [a, b] = arr; --- ⚡ 6. Skip Values const [first, , third] = arr; --- 🚀 Why it matters ✔ Cleaner and shorter code ✔ Easier data extraction ✔ Widely used in React (props, hooks) --- 💡 One-line takeaway: 👉 “Destructuring lets you pull out exactly what you need, cleanly.” --- Master this, and your code readability improves instantly. #JavaScript #Destructuring #WebDevelopment #Frontend #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