💡 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
Soumen Sarkar’s Post
More Relevant Posts
-
🌟 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
To view or add a comment, sign in
-
-
🧩 SK – Flatten a Nested Array in JavaScript 💡 Explanation (Clear + Concise) A nested array contains other arrays inside it. Flattening means converting it into a single-level array — an essential skill for data manipulation in React, especially when handling API responses or nested JSON data. 🧩 Real-World Example (Code Snippet) // 🧱 Example: Nested array const arr = [1, [2, [3, [4]]]]; // ⚙️ ES6 Method – flat() const flatArr = arr.flat(3); console.log(flatArr); // [1, 2, 3, 4] // 🧠 Custom Recursive Function function flattenArray(input) { return input.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), [] ); } console.log(flattenArray(arr)); // [1, 2, 3, 4] ✅ Why It Matters in React: When API data comes nested, flattening simplifies mapping through UI. Helps manage deeply nested state objects effectively. 💬 Question: Have you ever had to handle deeply nested data structures in your React apps? 📌 Follow Sasikumar S for more daily dev reflections, real-world coding insights & React mastery. 🤝 Connect Now: sasiias2024@gmail.com 💟 Visit: sk-techland.web.app ❤️ Follow our LinkedIn Page for more React & JavaScript growth tips. #JavaScript #ReactJS #ES6 #WebDevelopment #FrontendDeveloper #FlattenArray #JSFundamentals #CodingJourney #CareerGrowth
To view or add a comment, sign in
-
-
🔗 SK – Promise Chain: Sequential Data Fetching in JavaScript 💡 Explanation (Clear + Concise) Sometimes, you need to fetch data in sequence — for example, when the result of one API depends on another. That’s where Promise chaining shines. 🧩 Real-World Example (Code Snippet) // 🧠 Simulated APIs function getUser() { return Promise.resolve({ id: 1, name: "Sasi" }); } function getPosts(userId) { return Promise.resolve([`Post1 by User ${userId}`, `Post2 by User ${userId}`]); } // 🔗 Chaining Promises getUser() .then(user => { console.log("User:", user.name); return getPosts(user.id); }) .then(posts => { console.log("Posts:", posts); }) .catch(err => console.error(err)); // ⚙️ Modern async/await async function fetchData() { const user = await getUser(); const posts = await getPosts(user.id); console.log("Async/Await:", posts); } fetchData(); ✅ Why It Matters in React: Manage sequential API calls in effects or Redux Thunks. Cleaner logic for dependent API requests. Simplifies asynchronous workflows in modern React apps. 💬 Question: Do you prefer Promise chains or async/await in your React projects — and why? 📌 Follow Sasikumar S for more daily dev reflections, real-world coding insights & React mastery. 🤝 Connect Now: sasiias2024@gmail.com 💟 Visit: sk-techland.web.app ❤️ Follow our LinkedIn Page for more React & JavaScript growth tips. #JavaScript #ReactJS #Promises #AsyncAwait #FrontendDeveloper #WebDevelopment #JSFundamentals #CareerGrowth #CodingJourney
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
-
🚀 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
-
Can we have a boolean index signature in TypeScript? 🤔 In #javascript we can use any data to index object properties, but in reality the object will have only string keys, as the keys will be serialized. 💡 #typescript reflects this fact - it will display an error, when we use boolean, Date, Array or other values as an object property key. The exception is the number type, for which the compiler recognizes an index signature. This supports the array semantics, where we access properties sequentially, so we can do arr[i++] instead of arr[`${i++}`]. 👍 So what if we want to use the boolean values as object keys without typescript stopping us? I've explored this problem, not as a practical one, but as a type challenge. As it turns out the TypeScript mapped types and template literals are powerful enough to get this done. ⚡ Read more: https://lnkd.in/evxDp3Re
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
-
🔓 JS Tip: Stop Manually Assigning Object Properties! 🔓 Tired of writing var name = user.name; var email = user.email;? Destructuring lets you "pull apart" objects and arrays and grab just the pieces you need, all in one line. ❌ The Old Way (One by One) js code - var user = { id: 123, name: 'Alex', email: 'alex@example.com' }; var id = user.id; var name = user.name; var email = user.email; --- ✅ The New Way (Destructuring) js code - const user = { id: 123, name: 'Alex', email: 'alex@example.com' }; // "From 'user', get 'id', 'name', and 'email' // and put them in variables with the same name." const { id, name, email } = user; ---- 🔥 Why it's better: It's incredibly clean and efficient, especially with large objects from an API. You declare what data you want, not the tedious steps to get it. It's also perfect for function arguments and React props. 👉 View My New Services - https://lnkd.in/g5UaKeTc 🎇 Do you want more tips like this? Do follow and write "Yes" in the comment box. #javascriptTips #JavaScript #JSTips #ES6 #Developer #Programming #WebDev #ReactJS #NodeJS #Coding #TechTips #WebDeveloper #MdRedoyKayser #Webxpanda #WordPress
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
-
⚙️ Mastering JavaScript Data Types — The Foundation of Data Handling I’ve now explored one of the most fundamental concepts in JavaScript — Data Types. In JavaScript, every value has a data type that defines how it is stored, manipulated, and compared in memory. Being a dynamically typed language, JavaScript automatically determines the type of a variable at runtime — meaning you don’t need to declare it explicitly. 🔹 Classification of Data Types JavaScript data types are broadly divided into two categories: 🟢 1️⃣ Primitive Data Types Primitive data types represent single immutable values. ✅ Important Property: Primitive types are immutable (their actual values cannot be changed, only reassigned). 🔵 2️⃣ Non-Primitive (Reference) Data Types Non-primitive types are objects that store collections of data or more complex entities. ✅ Note: Arrays and Functions are technically objects in JavaScript. 🔍 Value vs Reference Behavior When assigning values: Primitive types → A copy of the value is created. Reference types → A memory reference is shared. ⚙️ Key Takeaways JavaScript has 7 primitive and 1 non-primitive (object) base category. Variables don’t have fixed types; values do. Understanding how data types are stored and referenced helps avoid bugs and memory issues. Type checking can be done using the typeof operator. Knowing how data is represented under the hood is what transforms code from “working” to “optimized.” Understanding data types lays the foundation for mastering JavaScript logic, memory, and performance. 💡 #JavaScript #WebDevelopment #Frontend #CodingJourney #LearnToCode #Programming #DataTypes #SoftwareEngineering #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