🚀 𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗟𝗶𝗳𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁: 𝗔 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 𝗧𝗵𝗿𝗼𝘂𝗴𝗵 𝗠𝗲𝗺𝗼𝗿𝘆 Ever wonder why some apps get sluggish over time? It’s usually a memory issue. In JS, we have an "𝗜𝗻𝘃𝗶𝘀𝗶𝗯𝗹𝗲 𝗝𝗮𝗻𝗶𝘁𝗼𝗿" (the Garbage Collector) who handles cleanup, but as engineers, we must ensure we don't accidentally "lock the broom closet." 1️⃣ 𝗧𝗵𝗲 𝗕𝗶𝗿𝘁𝗵: 𝗦𝘁𝗮𝗰𝗸 𝘃𝘀. 𝗛𝗲𝗮𝗽 JavaScript uses two distinct "storage rooms" for your data: • 𝗧𝗵𝗲 𝗦𝘁𝗮𝗰𝗸 (𝗙𝗮𝘀𝘁 & 𝗦𝘁𝗮𝘁𝗶𝗰): Stores Primitives (Numbers, Strings, Booleans). It follows a 𝗟𝗜𝗙𝗢 (Last-In, First-Out) structure. Access is nearly instantaneous. • 𝗧𝗵𝗲 𝗛𝗲𝗮𝗽 (𝗟𝗮𝗿𝗴𝗲 & 𝗗𝘆𝗻𝗮𝗺𝗶𝗰): Stores Non-Primitives (Objects, Arrays). It grows as needed but requires more management overhead. 𝗧𝗵𝗲 "𝗦𝗼 𝗪𝗵𝗮𝘁?": When you copy an object, you only copy the 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 (the address). If obj1 and obj2 point to the same heap address, modifying one changes the other. 💡 𝘗𝘳𝘰-𝘛𝘪𝘱: 𝘜𝘴𝘦 𝘴𝘵𝘳𝘶𝘤𝘵𝘶𝘳𝘦𝘥𝘊𝘭𝘰𝘯𝘦() 𝘧𝘰𝘳 𝘵𝘳𝘶𝘦 𝘥𝘦𝘦𝘱-𝘤𝘭𝘰𝘯𝘪𝘯𝘨. 2️⃣ 𝗧𝗵𝗲 𝗟𝗶𝗳𝗲𝗹𝗶𝗻𝗲: 𝗥𝗲𝗮𝗰𝗵𝗮𝗯𝗶𝗹𝗶𝘁𝘆 Your "right to exist" in JS is defined by 𝗥𝗲𝗮𝗰𝗵𝗮𝗯𝗶𝗹𝗶𝘁𝘆. An object is alive only if it can be reached from a 𝗥𝗼𝗼𝘁 (the window or global object). 𝗧𝗵𝗲 𝗦𝘂𝗿𝘃𝗶𝘃𝗮𝗹 𝗖𝗵𝗲𝗰𝗸𝗹𝗶𝘀𝘁: ✅ Is it a Root? (Global object) ✅ Is it referenced by a Root (e.g., a global variable)? ✅ Is it a local variable in a function currently running? ✅ Is it a property of an object that is itself reachable? 3️⃣ 𝗧𝗵𝗲 𝗚𝗿𝗲𝗮𝘁 𝗖𝗹𝗲𝗮𝗻𝘂𝗽: 𝗠𝗮𝗿𝗸-𝗮𝗻𝗱-𝗦𝘄𝗲𝗲𝗽 Modern engines use the 𝗠𝗮𝗿𝗸-𝗮𝗻𝗱-𝗦𝘄𝗲𝗲𝗽 algorithm: 1. 𝗠𝗮𝗿𝗸: The GC starts at the Roots and "paints" every reachable object. 2. 𝗦𝘄𝗲𝗲𝗽: It reclaims every bit of space occupied by the "unpainted" (unreachable) ones. 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁'𝘀 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: This solves the 𝗖𝗶𝗿𝗰𝘂𝗹𝗮𝗿 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 problem. If two objects point to each other but are disconnected from the Root, the Janitor recognizes they are "garbage" and clears them both. 4️⃣ 𝗖𝗼𝗺𝗺𝗼𝗻 𝗠𝗲𝗺𝗼𝗿𝘆 𝗟𝗲𝗮𝗸𝘀 A leak occurs when you leave a "string" attached to an object you no longer need: ⚠️ 𝗔𝗰𝗰𝗶𝗱𝗲𝗻𝘁𝗮𝗹 𝗚𝗹𝗼𝗯𝗮𝗹𝘀: Forgetting let/const pins data to the Root forever. ⚠️ 𝗙𝗼𝗿𝗴𝗼𝘁𝘁𝗲𝗻 𝗧𝗶𝗺𝗲𝗿𝘀: setInterval captures scope until clearInterval is called. ⚠️ 𝗢𝘂𝘁-𝗼𝗳-𝗗𝗢𝗠 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀: Removing a button visually but keeping it in a JS variable keeps it in RAM. 💡 𝗧𝗵𝗲 𝟯 𝗚𝗼𝗹𝗱𝗲𝗻 𝗥𝘂𝗹𝗲𝘀: 1. 𝗠𝗶𝗻𝗶𝗺𝗶𝘇𝗲 𝗚𝗹𝗼𝗯𝗮𝗹𝘀: Keep variables tightly scoped. 2. 𝗨𝘀𝗲 𝗪𝗲𝗮𝗸𝗠𝗮𝗽𝘀: Perfect for metadata; they don't prevent the Janitor from doing his job. 3. 𝗖𝗹𝗲𝗮𝗻 𝗬𝗼𝘂𝗿 𝗧𝗶𝗺𝗲𝗿𝘀: Treat every timer as a debt that must be paid back. What’s the toughest memory leak you’ve ever fixed? Share your story below! 👇 #JavaScript #WebDev #SoftwareEngineering #CodingTips #WebPerf #Programming
JavaScript Memory Management: Understanding Garbage Collection and Leaks
More Relevant Posts
-
JavaScript Performance Optimization: Frequency Counter Pattern While revisiting common algorithm patterns, I compared two approaches to solve a classic problem: Question: Check if the second array contains the squares of the first array with the same frequency. Example: arr1 = [1,2,3,2] arr2 = [9,1,4,4] ❌Approach 1: Using indexOf() + splice() (Naive Solution) -This approach searches the second array for every element of the first array. function same(arr1, arr2){ if(arr1.length !== arr2.length){ return false; } for(let i = 0; i < arr1.length; i++){ let correctIndex = arr2.indexOf(arr1[i] ** 2) if(correctIndex === -1){ return false; } arr2.splice(correctIndex,1) } return true; } ✅ Approach 2: Frequency Counter Pattern (Optimized Solution) - Instead of repeatedly searching arrays, we count occurrences using objects (hash maps) function same(arr1, arr2){ if(arr1.length !== arr2.length){ return false; } let frequencyCounter1 = {} let frequencyCounter2 = {} for(let val of arr1){ frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1 } for(let val of arr2){ frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1 } for(let key in frequencyCounter1){ if(!(key ** 2 in frequencyCounter2)){ return false } if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){ return false } } return true } 🚀 Key Takeaway (Big O Notation) Instead of repeatedly searching arrays: ❌ Nested lookups → O(n²) ✅ Frequency Counter → O(n) A small algorithmic improvement can make a big difference in performance, especially when working with large datasets. 💬 Curious to hear from other developers — What are your favorite JavaScript optimization patterns? #JavaScript #FrontendDevelopment #Algorithms #PerformanceOptimization #CodingPatterns #WebDevelopment
To view or add a comment, sign in
-
🤔 Ever copied an object with { ...obj } and thought you made a fully separate copy… then a nested value changed in both places? That’s the shallow vs deep copy trap in JavaScript. 🧠 JavaScript interview question What’s the difference between a shallow copy and a deep copy in JavaScript? ✅ Short answer A shallow copy copies only the top-level properties. If a property contains a nested object or array, the copy still points to the same reference. A deep copy creates a fully independent clone, including nested objects and arrays. 🔍 A bit more detail Shallow copy Top-level values are copied Nested objects/arrays are still shared Changing nested data affects both the original and the copy Common shallow copy methods: spread syntax: { ...obj } Object.assign() array methods like slice() and concat() Deep copy Clones nested structures too Changes in the copy do not affect the original Better when you need true independence Common deep copy approaches: structuredClone() custom recursive cloning JSON.parse(JSON.stringify(obj)) for simple JSON-safe data only 💻 Example const original = { name: "Alice", address: { city: "Miami" }, scores: [10, 20], }; const shallow = { ...original }; shallow.name = "Bob"; // affects only the copy shallow.address.city = "Tampa"; // affects both shallow.scores.push(30); // affects both console.log(original.address.city); // "Tampa" console.log(original.scores); // [10, 20, 30] Here, name is fine because it’s a primitive. But address and scores are nested references, so both objects still share them. 💻 Deep copy example const original = { date: new Date(), list: [1, 2, 3] }; const deep = structuredClone(original); deep.list.push(4); console.log(original.list); // [1, 2, 3] // Changing the original doesn't affect the copy original.date.setFullYear(2030); console.log(deep.date.getFullYear()); // original change has no effect ⚠️ Important gotchas { ...obj } does not make a deep copy Object.assign() is also shallow JSON.parse(JSON.stringify(obj)) loses things like: functions undefined Date objects as real Dates Map Set cyclic references So for modern JavaScript, structuredClone() is usually the safer built-in option when supported. 🎯 Real-world way to think about it A shallow copy is like copying a folder but keeping the same files inside. A deep copy is like duplicating the folder and duplicating every file inside it too. That’s why nested changes behave differently. 💡 When to use which Use shallow copy when: your data is flat nested data is intentionally shared you only need a quick top-level clone Use deep copy when: nested data must be fully independent you’re working with mutable complex state shared references could cause bugs That difference looks small in code, but it causes a lot of real bugs in apps. #javascript #webdevelopment #frontend #reactjs #softwareengineering #programming #coding #javascriptdeveloper #frontenddeveloper #interviewprep
To view or add a comment, sign in
-
I had a problem understanding what actually Heap Memory is in JavaScript, so I went through the topic. Sharing it here in a simple way. 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 𝗿𝗲𝗺𝗼𝘃𝗲𝘀 𝗺𝗲𝗺𝗼𝗿𝘆 𝗼𝗻𝗹𝘆 𝘄𝗵𝗲𝗻 𝗻𝗼𝘁𝗵𝗶𝗻𝗴 𝗶𝘀 𝗽𝗼𝗶𝗻𝘁𝗶𝗻𝗴 𝘁𝗼 𝗶𝘁.𝗜𝗳 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝘀𝘁𝗶𝗹𝗹 𝗵𝗮𝘀 𝗮 𝗿𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲, 𝗶𝘁 𝘀𝘁𝗮𝘆𝘀 𝗶𝗻 𝗺𝗲𝗺𝗼𝗿𝘆. In JS, memory is mainly divided into 2 parts: 1. 𝗦𝘁𝗮𝗰𝗸 𝗠𝗲𝗺𝗼𝗿𝘆:Stores primitive values (numbers, strings, booleans, etc.) and function call information. 2. 𝗛𝗲𝗮𝗽 𝗠𝗲𝗺𝗼𝗿𝘆:Stores objects, arrays, closures, and functions — anything reference-based. Heap memory issues happen when the application uses too much heap memory (large objects, leaks, closures). This can slow down the application and affect performance. 𝗪𝗵𝘆 𝗛𝗲𝗮𝗽 𝗠𝗲𝗺𝗼𝗿𝘆 𝗜𝘀𝘀𝘂𝗲𝘀 𝗢𝗰𝗰𝘂𝗿 1. 𝗠𝗲𝗺𝗼𝗿𝘆 𝗟𝗲𝗮𝗸𝘀 𝗱𝘂𝗲 𝘁𝗼 𝗨𝗻𝘂𝘀𝗲𝗱 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 When objects are no longer needed but still referenced, JS cannot remove them from memory. let storage = {}; function saveData() { const bigArray = new Array(1000000).fill("item"); storage.list = bigArray; // stored globally } saveData(); Even after saveData() finishes, memory is not freed because storage.list still holds the reference. 2. 𝗘𝘃𝗲𝗻𝘁 𝗟𝗶𝘀𝘁𝗲𝗻𝗲𝗿𝘀 𝗡𝗼𝘁 𝗥𝗲𝗺𝗼𝘃𝗲𝗱 If DOM elements are removed but their event listeners remain attached, memory may not be cleaned properly. const button = document.getElementById("myBtn"); function handleClick() { console.log("Button clicked"); } button.addEventListener("click", handleClick); button.remove(); // listener still exists Correct way: button.removeEventListener("click", handleClick); button.remove(); 3. 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗛𝗼𝗹𝗱𝗶𝗻𝗴 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 Closures can keep variables in memory as long as the function reference exists. function createCounter() { let number = 0; return function () { number++; console.log(number); }; } let counter = createCounter(); If no longer needed: counter = null; // reference removed 4. 𝗟𝗮𝗿𝗴𝗲 𝗜𝗻-𝗠𝗲𝗺𝗼𝗿𝘆 𝗗𝗮𝘁𝗮 Sometimes applications store large API responses in memory, which keeps growing. const userData = {}; async function getUser(id) { if (!userData[id]) { const response = await fetch(`/api/${id}`); const data = await response.json(); userData[id] = data; } return userData[id]; } If many IDs are stored, memory usage keeps increasing. If I missed something or you have better examples, feel free to share in the comments. Happy coding! 😊 #developer #frontenddeveloper #backenddeveloper #softwareengineer #sde #frontend #backend #javascript #webdev #coding #devtips #webdevelopment #softwaredevelopment #reactjs #JS #coding
To view or add a comment, sign in
-
Complete JavaScript Road Map A-Z JavaScript🎯 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS: 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest #LinkedIn #CareerGrowth #SuccessMindset #Networking #Leadership
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 You've probably heard that everything in JavaScript is an object. But what is an object? It's a collection of key-value pairs that lets you group related data under one variable. Think of it like a digital profile card - everything about that person lives in one place. You can create an object using object literal syntax - just curly braces {}: let person = { name: "Rahul", age: 22, city: "Kanpur" }; Objects become essential when your data has structure. Common use cases include: - User profiles - name, email, role, preferences - E-commerce products - title, price, stock, category - API responses - structured JSON data from servers - Game characters - health, position, inventory - Form data - collecting and validating user input You can read values from an object using dot notation or bracket notation: console.log(person.name); console.log(person["city"]); Objects are mutable by default. You can update any property using the assignment operator: person.age = 23; You can add new properties to an existing object at any time: person.profession = "Developer"; Use the delete keyword to remove a property entirely: delete person.city; To iterate over all properties in an object, use the for...in loop: for (let key in person) { console.log(key + " : " + person[key]); } JavaScript objects are the backbone of nearly every application you'll build. Practice creating objects for real scenarios and explore destructuring to pull values out cleanly. Source: https://lnkd.in/gde8pgUC
To view or add a comment, sign in
-
𝗧𝗼𝗽𝗶𝗰 𝟬𝟵: 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝘁𝗶𝗮𝗹 𝗘𝗾𝘂𝗮𝗹𝗶𝘁y JavaScript doesn't care if two objects look identical; it cares if they share the same address in memory. A seemingly harmless [1, 2, 3] === [1, 2, 3] evaluates to false, and this tiny fact is secretly destroying your React application's performance. Referential equality is the absolute gatekeeper of efficient re-rendering. • The Summary: In JavaScript, primitives (strings, numbers, booleans) are compared by their actual value. However, non-primitives (objects, arrays, functions) are compared by their reference—their physical location in the computer's memory. Referential equality means checking if two variables point to the exact same memory address, regardless of whether their internal contents match. • The Crux: 1. The === Trap: When used on objects or arrays, strict equality checks the memory pointer, not the deep contents. 2. The Dependency Array: React's useEffect, useMemo, and useCallback rely entirely on referential equality (Object.is) to decide if they should re-run. 3. Unnecessary Renders: Passing a brand new inline object or arrow function down as a prop breaks referential equality, forcing the child component to re-render even if the actual data hasn't changed. • The Deep Insight (Architect's Perspective): As architects, we know that rendering is just a downstream consequence of state evaluation. If you break referential equality by passing inline objects (like style={{ marginTop: 10 }}) or un-memoized functions, you are lying to the Virtual DOM. You are actively telling the engine, "this data is entirely new and unprecedented," when it is factually identical to the last frame. Mastering referential equality is how you tame the rendering cascade. It allows you to prune the update tree with surgical precision, ensuring that the engine only does work when the application state has genuinely evolved. • Tip: Extract static objects and arrays outside your component function. If a config object or a list of constants doesn't depend on component state or props, declaring it inside the component means re-creating it (new memory address) on every single render. Define it once at the module level to guarantee referential stability. #WebArchitecture #SoftwareEngineering #UbisageCodes #ObaidAshiq #React #NextJS #FrontendDevelopment #SystemArchitecture #SystemDesign #SoftwareArchitecture #CleanCode #JavaScript #StateManagement #FunctionalProgramming #Immutability #CodingBestPractices
To view or add a comment, sign in
-
-
Writing JavaScript from “logic in your mind” is less about syntax and more about thinking in structured steps. Here’s how to do it effectively: 🧠 1. Start with Plain English (Not Code) Before touching JS, describe your logic like you're explaining it to someone: 👉 Example: “I need to take a list of users, group them by role, and count how many are in each role.” Now your brain is clear—this becomes your blueprint. ✍️ 2. Break It Into Steps Convert that idea into small steps: 1.Loop through users 2.Check their role 3.Store role in an object 4.Increment count 👉 This is your algorithm ------------------------------------------------ 💻 3. Translate Steps → Code Now convert each step into JavaScript: const result = users.reduce((acc, user) => { const role = user.role; acc[role] = (acc[role] || 0) + 1; return acc; }, {}); 👉 Key idea: Each line should represent one thought. -------------------------------------------------- 🔄 4. Think in Patterns (Senior-Level Skill) Most problems fall into patterns: Transform data → map Filter data → filter Aggregate → reduce Lookup → object / Map Async flow → async/await 👉 Don’t reinvent logic—recognize patterns ---------------------------------------------------- 🧩 5. Use “Input → Output” Thinking Always ask: -What is the input? -What should the output look like? 👉 Example: // Input [1, 2, 3] // Output [2, 4, 6] Now solution becomes obvious: arr.map(x => x * 2) -------------------------------------------------- ⚙️ 6. Think in Data Transformations Modern JavaScript is about data flow, not step-by-step mutation. ❌ Imperative: let result = []; for (let i = 0; i < arr.length; i++) { result.push(arr[i] * 2); } ✅ Declarative: const result = arr.map(x => x * 2); --------------------------------------------------- 🔍 7. Debug Your Thinking (Not Just Code) If stuck, ask: What exactly is failing? Which step is wrong? What is the current vs expected output? 👉 Use logs smartly: console.log({ step: 'after filter', data }); ------------------------------------------------------ 💡 8. Practice “Thinking in Code” Best way to improve: Solve problems daily (LeetCode, real-world) Rebuild features (search, pagination, debounce) Read other people’s code ------------------------------------------------------- Bonus: 🔥 Simple Framework to Remember Idea → Steps → Pattern → Code → Refactor
To view or add a comment, sign in
-
-
Most developers think web scraping = curl + regex. That mindset breaks on 80% of modern sites. 🕸️ JavaScript changed everything. Pages now render in the browser, not on the server. If you're only fetching raw HTML, you're missing half the data. Here's the full JS scraping pipeline you actually need: 1️⃣ Static sites → use fetch() or axios Fast, lightweight, no browser overhead. Works if the data is in the initial HTML response. 2️⃣ Dynamic JS-rendered sites → use Puppeteer or Playwright Launches a real headless Chromium instance. Waits for the JavaScript to execute before extracting. 3️⃣ Parse & Extract → Cheerio (server-side jQuery) or querySelector CSS selectors: document.querySelectorAll('.product-price') Cheerio: $('h2.title').text() 4️⃣ Watch out for anti-bot defences: - Rate limits (429 Too Many Requests) - CAPTCHAs blocking headless browsers - robots.txt — always check it first - Dynamic tokens embedded in JS - Terms of Service restrictions 5️⃣ Output → JSON, CSV, or directly into a database Quick rule of thumb: → Data in the HTML source? Use fetch + Cheerio. → Data loads after a click/scroll? Use Playwright. The tools are free. The knowledge of when to use each one is what separates a working scraper from a broken one. What JS scraping challenge have you run into lately? 👇 #WebScraping #JavaScript #Puppeteer #Playwright #NodeJS
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 19 Objects are powerful… But real-world data is rarely simple 😵 Imagine this 👇 A user profile: let user = { name: "Abhay", address: { city: "Delhi", pincode: 110001 } } Now you want to access city: console.log(user.address.city) Works fine ✅ But what if address doesn’t exist? 😳 👉 Error ❌ 🔥 Solution → Optional Chaining (?.) Optional chaining helps you safely access nested data console.log(user.address?.city) 👉 If address exists → value milega 👉 If not → undefined (no error) ✅ 🔹 Nested Objects Objects ke andar objects ho sakte hain: let user = { name: "Abhay", skills: { frontend: "React", backend: "Node" } } 👉 Real-world data is always nested 🔹 Dynamic Keys Kabhi keys fixed nahi hoti 😎 let key = "name" let user = { [key]: "Abhay" } console.log(user.name) 👉 Output: Abhay 📌 Useful when key runtime par decide hoti hai 🔥 Real Life Example API data 📦 let response = { user: { profile: { username: "abhay123" } } } Safe access: console.log(response.user?.profile?.username) 👉 No crash even if data missing 🔥 Simple Summary Nested Object → object inside object Optional Chaining → safe access Dynamic Keys → flexible keys 💡 Programming Rule Real-world data is messy. Write code that handles it safely. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 18 Imagine this 👇 You have an object: ```javascript id="sr1" let user = { name: "Abhay", age: 22 } ``` Now you want to: 👉 Copy this object 👉 Add new data 👉 Merge with another object Will you manually copy everything? ❌ Messy… error-prone… not scalable --- ## 🔥 Solution → Spread & Rest Operator (...) That `...` (three dots) is more powerful than you think 😎 --- ## 🔹 1. Spread Operator (Expand / Copy) Spread is used to **expand values** ```javascript id="sr2" let user = { name: "Abhay", age: 22 } let newUser = { ...user } console.log(newUser) ``` 👉 Output: { name: "Abhay", age: 22 } 📌 Creates a **copy of object** --- ## 🔹 Add new properties ```javascript id="sr3" let updatedUser = { ...user, city: "Delhi" } ``` 👉 Output: { name: "Abhay", age: 22, city: "Delhi" } --- ## 🔹 Merge objects ```javascript id="sr4" let extra = { country: "India" } let merged = { ...user, ...extra } ``` 👉 Combines both objects --- ## 🔹 2. Rest Operator (Collect values) Rest is used to **collect remaining values** ```javascript id="sr5" let { name, ...rest } = { name: "Abhay", age: 22, city: "Delhi" } console.log(name) console.log(rest) ``` 👉 Output: Abhay { age: 22, city: "Delhi" } 📌 Rest gathers remaining data --- ## 🔥 Real Life Example Think of updating a profile 👤 Old data + new changes → merge 👉 Spread helps combine 👉 Rest helps extract --- ## 🔥 Simple Summary Spread → expand / copy / merge Rest → collect remaining data --- ### 💡 Programming Rule **Don’t rewrite data. Reuse and extend it smartly.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
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