🚀 Master Object Destructuring & JSON APIs in JavaScript!
JavaScript makes handling objects easy & efficient with destructuring and JSON APIs. Let’s break it down! 💡
📌 Object Destructuring – Extract Data Easily
Instead of accessing properties one by one, destructuring makes it simple & clean!
✅ Without Destructuring:
const user = { name: "Shubham", age: 25, city: "Pune" }; console.log(user.name, user.age, user.city);
✅ With Destructuring:
const { name, age, city } = user; console.log(name, age, city); // "Shubham", 25, "Pune"
💡 Less code, better readability!
🔹 Nested Object Destructuring
✅ Extract values from nested objects:
const employee = { info: { name: "John", role: "Developer" } }; const { info: { name, role } } = employee; console.log(name, role); // "John", "Developer"
🔹 Destructure with Default Values
✅ Avoid undefined when a property is missing:
const { country = "India" } = user; console.log(country); // "India" (default value)
📌 JSON & APIs – The Backbone of Web Apps!
🔹 What is JSON?
JSON (JavaScript Object Notation) is a lightweight format for storing & transferring data between a server & client.
✅ JSON Example:
{ "name": "Shubham", "age": 25, "skills": ["JavaScript", "React", "Node.js"] }
🔹 Fetching Data from an API (Real-World Example)
✅ Use fetch() to get JSON data from an API:
fetch("https://jsonplaceholder.typicode.com/users/1") .then(response => response.json()) // Convert response to JSON .then(data => console.log(data)) // Work with the data .catch(error => console.error("Error fetching data:", error));
💡 APIs send data in JSON format, and JavaScript converts it into an object for easy use!
🔹 Converting JSON to Object & Vice Versa
✅ Parse JSON to JavaScript Object:
const jsonData = '{"name":"Alice","age":30}'; const obj = JSON.parse(jsonData); console.log(obj.name); // "Alice"
✅ Convert JavaScript Object to JSON:
const jsonString = JSON.stringify(obj); console.log(jsonString); // '{"name":"Alice","age":30}'
📌 Key Takeaways:
✔️ Object destructuring makes code cleaner & efficient ✔️ JSON is used for data exchange between APIs & web apps ✔️ APIs send data in JSON format, which we can fetch & use ✔️ Use JSON.parse() & JSON.stringify() for conversion
Which feature do you use most? Let me know in the comments! 💬👇
#JavaScript #JSON #API #WebDevelopment #Coding #Programming #MERN #Frontend #100DaysOfCode
Data Scientist Intern
6moGood One 👍