🌟 Day 53 of JavaScript 🌟 🔹 Topic: Fetch API 📌 1. What is the Fetch API? The Fetch API allows JavaScript to make HTTP requests (like GET, POST, PUT, DELETE) to servers — used to retrieve or send data 🌐 💬 Think of it as JavaScript’s way to talk to web servers asynchronously. ⸻ 📌 2. Basic Syntax: fetch("https://lnkd.in/gXUzR2fM") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error)); ✅ Step-by-step: 1️⃣ Fetch sends the request 2️⃣ Waits for the response 3️⃣ Converts it (like .json()) 4️⃣ Handles the data or errors ⸻ 📌 3. Using async/await: async function getData() { try { const response = await fetch("https://lnkd.in/gXUzR2fM"); const data = await response.json(); console.log(data); } catch (err) { console.error("Fetch failed:", err); } } getData(); ⚙️ Cleaner, more readable syntax for async operations. ⸻ 📌 4. POST Example: fetch("https://lnkd.in/gJ4WB7DB", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Pavan", age: 25 }) }); ⸻ 📌 5. Why Use Fetch API? ✅ Simpler than XMLHttpRequest ✅ Promise-based ✅ Works with async/await ✅ Built-in for browsers ⸻ 💡 In short: The Fetch API makes calling APIs in JavaScript simple, powerful, and modern — the go-to tool for all web requests 🚀 #JavaScript #100DaysOfCode #FetchAPI #WebDevelopment #FrontendDevelopment #CodingJourney #JavaScriptLearning #CleanCode #AsyncJS #Promises #DevCommunity #CodeNewbie #WebDev
"Learn Fetch API for JavaScript in 5 steps"
More Relevant Posts
-
🔖React Tip: When Your “id” Isn’t Really Unique Recently ran into an interesting issue while working with API data in React. I was rendering a table and opening a popup when clicking on a cell - seemed simple enough. The API response looked like this: [ { id: "101", name: "101", age: 25 }, { id: "102", name: "102", age: 27 } ] Both `id` and `name` had the same values, and I didn’t think much of it at first. But when I opened the popup from the ID cell, it sometimes showed the wrong record or didn’t update at all. Here’s what the code looked like: {data.map((item) => ( <tr key={item.id}> <td onClick={() => openPopup(item.id)}>{item.id}</td> <td>{item.name}</td> </tr> ))} ⁉️The problem? React uses the `key` prop to identify DOM elements. If multiple rows share the same key value, React may reuse elements incorrectly. Also, since the popup logic was using `id` for lookup, it always returned the first matching record. Here’s the safer version: {data.map((item, index) => ( <tr key={index}> <td onClick={() => openPopup(item)}>{item.id}</td> <td>{item.name}</td> </tr> ))} And the popup handler: const openPopup = (rowData) => setSelected(rowData); 🧠Lesson learned: even something as small as duplicate `id` fields can cause surprising bugs in React tables. Always make sure your keys are unique and your popup or event logic doesn’t rely on repeated identifiers. #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #ReactTips
To view or add a comment, sign in
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲: 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗙𝗲𝘁𝗰𝗵 𝗔𝗣𝗜 💡 Say goodbye to old-school XMLHttpRequest! The Fetch API is the modern, promise-based way to make HTTP requests in JavaScript — simple, powerful, and elegant. ⚡ 🔹 𝗕𝗮𝘀𝗶𝗰 𝗙𝗲𝘁𝗰𝗵 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: fetch('https://lnkd.in/gWKpgMrT') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ✅ fetch() returns a Promise ✅ response.json() converts response to JSON ✅ .catch() ensures error handling 🔹 𝗖𝗹𝗲𝗮𝗻𝗲𝗿 𝗦𝘆𝗻𝘁𝗮𝘅 𝘄𝗶𝘁𝗵 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁: async function getData() { try { const response = await fetch('https://lnkd.in/gWKpgMrT'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getData(); ✨ No more nested .then() chains — just clean, readable async code! 💡 𝗣𝗿𝗼 𝗧𝗶𝗽𝘀: 🔸 Always handle network errors 🔸 Add headers for authentication & content-type 🔸 Supports GET, POST, PUT, DELETE and more Credit 💳 🫡 Sameer Basha Shaik 🚀 The Fetch API is a must-know tool for every frontend developer — perfect for fetching data, integrating APIs, and building modern web applications! 🌐 #JavaScript #FetchAPI #WebDevelopment #AsyncAwait #Frontend #CodingTips #CleanCode #DeveloperCommunity #Promises #LearnToCode #jsdeveloper
To view or add a comment, sign in
-
Day 76 of #100daysOfCode Understanding the Fetch API and Promises in JavaScript Today I learned about how the Fetch API works and how it connects with Promises in handling asynchronous operations. The Fetch API is what allows web applications to make network requests, retrieving or sending data to a server. A simple example looks like this: fetch('api.example.com/data') By default, fetch() makes a GET request, which is used to retrieve data. To work with the returned data, we usually convert it to JSON first: fetch('api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) Using the .then() method, we can handle the data once it’s ready — this is where Promises come in. A Promise represents the result of an asynchronous operation that may complete successfully or fail. Fetch isn’t limited to just GET requests, it can also handle: POST (send data to the server) PUT (update existing data) DELETE (remove data) We also use response.json() to parse the data before using it in our app. Common types of resources fetched from the network include APIs for weather data, country lists, or even media files like images, audio, and video. I also learned about Promise chaining, which lets us perform multiple async tasks in sequence: fetch('api.example.com/data') .then(res => res.json()) .then(data => fetch('api.example.com/more-data')) .then(res => res.json()) .then(moreData => console.log(moreData)) .catch(error => console.error('Error:', error)) The .catch() method handles any error in the entire chain, keeping our code cleaner and more predictable. Today’s lesson helped me understand how data actually flows between the client and server in modern JavaScript apps, and why promises are such a powerful tool for managing that flow.
To view or add a comment, sign in
-
💡 JavaScript Tip of the Day Want to update a specific object value from an API response? Here’s a clean and modern way to do it using async/await and .map() 👇 const fetchData = async () => { const response = await fetch("https://lnkd.in/gQTYNBSX"); const data = await response.json(); const updatedData = data.map((user) => user.name === "Ervin Howell" ? { ...user, username: "Sarkar" } : user ); console.log(updatedData); }; fetchData(); 🧠 Why it’s useful: Makes async operations clean and readable Keeps data immutable using object spread { ...user } Updates only what’s needed — nothing more A simple yet powerful approach to handle dynamic data updates! 🚀 hashtag #JavaScript hashtag #WebDevelopment hashtag #FrontendDeveloper hashtag #AsyncAwait hashtag #CodingTips hashtag #WebDev hashtag #UIDeveloper hashtag #ReactJS
To view or add a comment, sign in
-
-
Coercion: The hidden mechanics of JS type conversion JavaScript can do some surprising things when combining different data types — and it’s not “random”, it follows a set of internal rules. I built a tiny Coercion Lab that: • Breaks down implicit & explicit type conversion • Shows how JavaScript compares values (== vs ===) • Demonstrates why expressions you see every day behave the way they do • Helps you build deeper intuition for debugging and writing safe code I did my best to complete it, waiting for your feedback 😊 Repo: https://lnkd.in/gfAyiXjd Tech: JavaScript (ES2023), Node, CLI Goal: Understand how JavaScript thinks
To view or add a comment, sign in
-
🚀 Day 84/90 – #90DaysOfJavaScript Topic covered: Copying by Reference vs Value in JavaScript ✅ Reference vs Value 👉 Primitive types (string, number, boolean, etc.) are copied by value. 👉 Objects and arrays are copied by reference, meaning both variables point to the same memory. ✅ Copying Arrays 👉 Shallow Copy: Creates a new top-level array but shares nested references. 👉 Methods: slice(), spread ([...]), Array.from(). 👉 Deep Copy: Fully duplicates nested data. 👉 Methods: structuredClone(), JSON.parse(JSON.stringify()) (⚠️ limited for special data types). ✅ Copying Objects 👉 Assignment (=) copies the reference. 👉 Shallow Copy: Object.assign({}, obj) or {...obj} — nested objects still shared. 👉 Deep Copy: 👉 structuredClone(obj) ✅ 👉 JSON.parse(JSON.stringify(obj)) ⚠️ (loses functions, undefined, etc.) ✅ Key Takeaways 👉 Shallow copy affects nested objects/arrays. 👉 structuredClone() is the most reliable modern solution for deep cloning. 👉 Always choose cloning method based on data type and depth of structure. 🛠️ Access my GitHub repo for all code and explanations: 🔗 https://lnkd.in/d3J47YHj Let’s learn together! Follow my journey to #MasterJavaScript in 90 days! 🔁 Like, 💬 comment, and 🔗 share if you're learning too. #JavaScript #WebDevelopment #CodingChallenge #Frontend #JavaScriptNotes #MasteringJavaScript #GitHub #LearnInPublic
To view or add a comment, sign in
-
How JavaScript Handles Memory Every program needs memory to store data, and JavaScript is no different. When you declare variables, objects, or functions, JS allocates memory for them in two main areas: the Stack and the Heap. #Stack: Used for primitive values (like numbers, strings, booleans) and function calls. It’s fast and simple — data is stored and removed in a Last-In-First-Out (LIFO) order. #Heap: Used for objects, arrays, and functions — anything that can grow in size or be referenced. It’s more flexible but slower because data is stored dynamically and accessed through references. Here’s a quick example 👇 let a = 10; // stored in Stack let b = { name: "Ali" }; // stored in Heap let c = b; // c points to same Heap reference c.name = "Akmad"; console.log(b.name); // "Ahmad" — both point to same object Here, both b and c point to the same memory in the Heap, which is why updating one affects the other. Understanding this helps prevent reference-related bugs. Now comes the smart part — Garbage Collection 🧹. JavaScript automatically frees up memory that’s no longer accessible. This is managed by an algorithm called Mark and Sweep, which “marks” objects still reachable from the global scope and removes the rest. But be careful — if you accidentally keep references alive (like global variables or event listeners), JS can’t clean them up. That’s how memory leaks happen. In short, memory management in JS is mostly automatic, but understanding it helps you write efficient code. You’ll learn to manage references better, avoid leaks, and appreciate just how elegantly JavaScript balances power and simplicity. #JavaScript #MemoryManagement #WebDevelopment #MERNStack #NodeJS #ReactJS #Frontend #CodingCommunity #LearnInPublic #100DaysOfCode #DeveloperJourney
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (the right way!) Most of us have tried this at least once: const clone = JSON.parse(JSON.stringify(obj)); …and then realized it breaks when the object has functions, Dates, Maps, or undefined values 😬 Let’s fix that 👇 ❌ The Problem with JSON.parse(JSON.stringify()) >It’s quick, but it: >Removes functions >Converts Dates into strings >Skips undefined, Infinity, and NaN >Fails for Map, Set, or circular references ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). It can handle Dates, Maps, Sets, and even circular references — no errors, no data loss. const deepCopy = structuredClone(originalObject); Simple, native, and reliable 💪 ✅ Option 2: Write Your Own Recursive Deep Clone Useful for older environments or if you want to understand the logic behind cloning. 💡 Pro Tip: If you’re working with complex or nested data structures, always prefer structuredClone(). It’s the modern, built-in, and safest way to deep clone objects in JavaScript. 🔥 Found this useful? 👉 Follow me for more JavaScript deep dives made simple — one post at a time. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
To view or add a comment, sign in
-
🚀 Let’s talk about something every beginner confuses — JavaScript Objects vs JSON Strings 💡 👉 JavaScript Object It’s the real, usable data inside your code. Example: const user = { name: "Anas", age: 21 }; You can access it directly: user.name → gives you "Anas" 👉 JSON String It’s the text version of that object — like saving it in a file or sending it over the internet. Example: const jsonString = '{"name": "Anas", "age": 21}'; Looks similar, but it’s just text — you can’t do jsonString.name because it’s not an object yet! 💡 Real-world use case: When your app talks to a server — say a weather app fetching data — the server sends info as JSON strings. Your JavaScript code then converts it into an object using: const data = JSON.parse(jsonString); …and now you can use it easily! 🧠 Think of it like this: Object → your living data inside JS JSON → a suitcase carrying that data safely to another computer 💼 #JavaScript #WebDevelopment #Beginners #CodingSimplified #JSON #Frontend
To view or add a comment, sign in
-
-
Going back to basics 🌱 Where Javascript stores Your data "Stack" vs "Heap Memory" ? have you ever wondered where your values are actually stored ? JavaScript manages memory in two main places - 1. "Stack Memory" Used for primitive values (like numbers, strings, booleans) and function calls. It is small but super fast. 2. "Heap Memory" Used for objects, arrays, and functions (reference types). It is larger and used for dynamic data that can grow or shrink. When Javascript executes the code, the "Stack" holds the variable name directly, while user stores only a reference (a pointer) to the object, and that object actually lives in the "Heap". So when you pass "user" around, you are really passing a "reference" to the data in the "heap" not the data itself. #JavaScript #Frontend
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