💡Don't Use Array Spread Operator In Every Case💡 Yes, you heard that right. If you have a very large data set, then using array spread operator to create a new array will slow down your application and you might receive, "Maximum call stack size exceeded" error. So instead of using array spread operator, use array concat method. const largeArray = [/* your large array */]; const newArray = [/* additional items */]; // Using spread operator (slow for large arrays) const combinedArray1 = [...largeArray, ...newArray]; // Using concat method (more efficient for large arrays) const combinedArray2 = largeArray.concat(newArray); So If you have a very large array, then avoid using spread operator, instead use array concat method. This is because spread operator creates a new array which means each spread operator like …arr1, …arr2 will create a new array and then iterates and then returns a new array. For example, with const result = […arr1, …arr2], javascript will create three arrays one for the result and one for each spread operator (and then iterates it) If we use the same for concat method then there would be one array creation which is result meaning the concat method directly iterates the array. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #typescript #webdevelopment
Avoid Array Spread Operator for Large Arrays
More Relevant Posts
-
🚀 map() vs. forEach(): Do you know the difference? The Hook: One of the first things we learn in JavaScript is how to loop through arrays. But using the wrong method can lead to "hidden" bugs that are a nightmare to fix. 🛑 🔍 The Simple Difference: ✅ .map() is for Creating. Use it when you want to take an array and turn it into a new one (like doubling prices or changing names). It doesn't touch the original data. ✅ .forEach() is for Doing. Use it when you want to "do something" for each item, like printing a message in the console or saving data to a database. It doesn't give you anything back. 💡 Why should you care? 1. Clean Code: .map() is shorter and easier to read. 2. React Friendly: Modern frameworks love .map() because it creates new data instead of changing the old data (this is called Immutability). 3. Avoid Bugs: When you use .forEach() to build a new list, you have to create an empty array first and "push" items into it. It’s extra work and easy to mess up! ⚡ THE CHALLENGE (Test your knowledge! 🧠) Look at the image below. Most developers get this wrong because they forget how JavaScript handles "missing" returns. What do you think is the output? A) [4, 6] B) [undefined, 4, 6] C) [1, 4, 6] D) Error Write your answer in the comments! I’ll be replying to see who got it right. 👇 #JavaScript #JS #softwareEngineer #CodingTips #LearnToCode #Javascriptcommunity #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
-
One small pattern I really like in JavaScript/TypeScript: return data.items .slice(offset, offset + limit) .map(({ id, firstName, lastName, companyId }) => ({ id, firstName, lastName, companyId, })); Why this is clean: • slice(offset, offset + limit) → handles pagination in a single, readable step • map(...) → transforms data immediately, returning only what’s needed • Object destructuring → avoids repetitive item.id, item.firstName, etc. • No mutations → everything is predictable and functional It’s concise, readable, and does exactly what it needs — nothing more. Sometimes clean code is just about using the right built-in methods. #JavaScript #TypeScript #CleanCode #javascript #remote
To view or add a comment, sign in
-
Three dots that changed JavaScript: ... The spread operator in action: Arrays: // Copy const copy = [...original] // Merge const all = [...arr1, ...arr2] // Add items const updated = [...items, newItem] Objects: // Copy const clone = { ...user } // Merge const combined = { ...defaults, ...config } // Update const modified = { ...user, age: 30 } Function calls: Math.max(...numbers) fetch(url, { ...defaultOptions, ...customOptions }) Before spread operator: const copy = original.slice() const merged = Object.assign({}, obj1, obj2) fn.apply(null, args) After spread operator: const copy = [...original] const merged = { ...obj1, ...obj2 } fn(...args) The magic: → No mutation (safer code) → Cleaner syntax → Works with any iterable → Essential for React state → Makes immutability easy Three dots. Infinite possibilities.
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
-
Here are your 37 topics organized by section: Execution, Scope & Memory 1. Execution context & call stack 2. var, let, const (scope + hoisting + TDZ) 3. Lexical scope & scope chain 4. Closures (behavior, not definition) 5. Shadowing & illegal shadowing 6. Garbage collection basics & memory leaks Functions & this 7. Function declarations vs expressions 8. this binding rules (default, implicit, explicit, new) 9. call, apply, bind 10. Arrow functions vs normal functions 11. Currying & partial application 12. Higher-order functions Async JavaScript 13. Event loop (call stack, microtasks, task queue) 14. Promises & chaining 15. async / await (error handling & sequencing) 16. Race conditions & stale closures 17. Timers (setTimeout, setInterval) vs microtasks 18. Promise utilities (all, allSettled, race, any) Data, References & ES6+ 19. == vs ===, truthy / falsy & type coercion deep dive 20. Object & array reference behavior 21. Deep vs shallow copy 22. Destructuring, rest & spread 23. Map, Set, WeakMap, WeakSet Prototypes & OOP 24. Prototype chain & Object.create() 25. class syntax vs prototype under the hood 26. Inheritance patterns Error Handling 27. try/catch with async/await edge cases 28. Custom error types 29. Unhandled promise rejections Modules 30. ES Modules (import/export) vs CommonJS (require) 31. Tree shaking concept 32. Dynamic imports — import() Iterators & Generators 33. Symbol.iterator & iterable protocol 34. Generator functions (function*) 35. Connecting generators to RxJS mental model Browser & Runtime Fundamentals 36. Event bubbling, capturing, delegation, preventDefault vs stopPropagation 37. DOM vs Virtual DOM, Reflow vs repaint, Web storage, Polyfills #angular #javascript #html #css #webdeveloper #angularDeveloper
To view or add a comment, sign in
-
𝗪𝗵𝗮𝘁'𝘀 𝗗𝗧𝗢𝘀 𝗶𝗻 𝗡𝗲𝘀𝘁 𝗷𝘀 In NestJS, a 𝗗𝗧𝗢 (Data Transfer Object) is an object that defines how data is sent over the network. Think of it as a contract or a blueprint that specifies exactly what data a client (like a mobile app or a browser) must send to your server. While DTOs are a general software pattern, NestJS uses them powerfully to handle validation and type safety. 𝟭. 𝗪𝗵𝘆 𝗱𝗼 𝘄𝗲 𝘂𝘀𝗲 𝗗𝗧𝗢𝘀? Without a DTO, your application wouldn't know if the incoming data is correct. If a user tries to register but sends a "username" as a number instead of a string, your database might crash. DTOs help prevent this by: 𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻: Ensuring the data has the right format, length, and type. 𝗗𝗮𝘁𝗮 𝗧𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺𝗮𝘁𝗶𝗼𝗻: Stripping away unwanted data that the client shouldn't be sending (e.g., trying to set their own isAdmin status). 𝗧𝘆𝗽𝗲 𝗦𝗮𝗳𝗲𝘁𝘆: Providing IntelliSense and auto-completion in your code so you know exactly what properties exist on the request body. 𝟮. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝘃𝘀. 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 In NestJS, it is highly recommended to use Classes for DTOs rather than Interfaces. 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 are removed during JavaScript compilation, meaning NestJS cannot check them at runtime. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 are preserved in the final code, allowing NestJS to use Pipe validation to check data as it arrives. #Programming #BackendDevelopment #TypeScript #NestJS
To view or add a comment, sign in
-
🧩 Demystifying the Node.js Event Loop: It's Not Just One Thread! Ever wondered what actually happens when you call setTimeout(() => {}, 1000)? Most people say "Node is single-threaded," but that’s only half the story. Here is the visual breakdown of how Node.js orchestrates asynchronous magic using libuv: 1. The Handoff (Main Thread) When you set a timer, the Main JS thread (V8) doesn't wait. It registers the callback and duration with libuv and moves on to the next line of code. 2. The Engine Room (libuv) This is where the heavy lifting happens. libuv maintains a Min-Heap—a highly efficient data structure that sorts timers by their expiration time. It puts the thread to "sleep" using OS-level polling (like epoll or kqueue) until the nearest timer is ready. 3. The Queue & The Tick Once the time arrives, libuv moves your callback into the Callback Queue. But it doesn't run yet! The Event Loop must cycle back to the "Timers Phase" to pick it up. ⚠️ The "Golden Rule" of Node.js Don't block the loop. If you run a heavy synchronous operation (like a massive while loop), the Event Loop gets stuck. Even if your timer has expired in the background, the Main Thread is too busy to check the queue. This is why a setTimeout(cb, 100) might actually take 5 seconds to fire if your main thread is congested. Key Takeaway: Node.js is fast because it offloads waiting to the OS via libuv, keeping the main thread free for execution. Keep your synchronous tasks light, and let the loop do its job! 🌀 #NodeJS #WebDevelopment #SoftwareEngineering #Backend #Javascript #ProgrammingTips
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
-
-
Subject - Common mistake while using fetch in JavaScript Many beginners (including me) try to do this: const data = await fetch('https://lnkd.in/gNBBq58S'); const json = await JSON.stringify(data); 🚫 This is wrong because fetch() returns a Response object, not actual JSON data. ✅ Correct approach: const data = await fetch('https://lnkd.in/gNBBq58S'); const json = await data.json(); ✔️ Lesson: Always use .json() to extract data from the response. Small mistake, but important for real-world projects. #javascript #webdevelopment #frontend #coding #learninpublic
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
-
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