JavaScript Simplified: Destructuring & Spread Operator Ever noticed how JavaScript lets you write cleaner and shorter code? That’s where Destructuring and the Spread Operator (...) come in! What is Destructuring? Destructuring means “unpacking” values from arrays or objects into variables— instead of accessing each one manually. const user = { name: "Sameer", age: 22 }; const { name, age } = user; console.log(name, age); // Sameer 22 You can even rename or set default values: const { country: location = "India" } = user; What is the Spread Operator (...)? The spread operator helps you copy, merge, or expand arrays and objects effortlessly. const fruits = ["apple", "banana"]; const moreFruits = ["orange", "grapes"]; const allFruits = [...fruits, ...moreFruits]; console.log(allFruits); // ["apple", "banana", "orange", "grapes"] It also works great with objects: const user = { name: "Sameer", age: 22 }; const updatedUser = { ...user, age: 23 }; console.log(updatedUser); // { name: "Sameer", age: 23 } In short: Destructuring → Pull out values easily Spread → Copy or merge effortlessly #JavaScript #WebDevelopment #Frontend #CodingTips #Destructuring #SpreadOperator #LearnJS
How to Simplify JavaScript with Destructuring and Spread Operator
More Relevant Posts
-
🍏 JS Daily Bite #10 — JavaScript Prototype Chains: A Full Comparison Master JavaScript's prototype-based inheritance system by exploring ways to create and manipulate prototype chains, their trade-offs, and best practices. 🏗️ Methods for Creating Prototype Chains: 1️⃣ Object Literal Syntax with __proto__ ✅ Standardized, optimized, more performant than Object.create() ✅ Ergonomic for declaring properties at creation ⚠️ Fails silently when pointing to non-objects 2️⃣ Constructor Functions ✅ Fast, standard, JIT-optimizable ⚠️ Methods are enumerable by default, inconsistent with class syntax ⚠️ Error-prone for longer inheritance chains 3️⃣ Object.create() ✅ Direct prototype setting at creation ✅ Can create objects with null prototype ⚠️ Verbose, error-prone, potentially slower than literals 4️⃣ Classes (ES6+) ✅ Ideal for complex inheritance with readability and maintainability ✅ Supports private elements ⚠️ Less optimized than traditional constructors 🔧 Mutating Existing Prototype Chains: 1️⃣ Object.setPrototypeOf() ✅ Modify the prototype of existing objects ⚠️ Can disrupt engine optimizations 💡 Best practice: set prototype during object creation 2️⃣ The __proto__ Accessor ⚠️ Fails silently with non-objects ⚠️ Non-standard and deprecated 💡 Recommendation: use Object.setPrototypeOf() instead ⚡ Performance Considerations: 1️⃣ Prototype Chain Lookup Costs Deep chains slow property access Non-existent properties traverse the entire chain All enumerable properties in the chain are iterated 2️⃣ Checking Own Properties Use hasOwnProperty() or Object.hasOwn() Don’t rely solely on undefined checks 🔜 Next in the Series: Enumerability and ownership of properties #JavaScript #JSDailyBite #WebDevelopment #Programming #LearnToCode #Prototypes #Inheritance #SoftwareEngineering #FrontendDevelopment #JSFundamentals #TechEducation
To view or add a comment, sign in
-
☑ Today I Learned: JavaScript Event Loop 🔁 ✍ The Event Loop is one of the most interesting parts of JavaScript. As we know, JavaScript is a single-threaded language — means ek time pe ek hi task perform kar sakta hai. But still JS handle karta hai multiple tasks like setTimeout, fetch, Promise, etc. — bina hang hue 😎 👉 The Event Loop ka main kaam hota hai ye check karna ki Call Stack empty hai ya nahi. Agar empty hai, to wo Microtask Queue (Promises) ya Callback Queue (setTimeout) me se tasks uthata hai aur Stack me daal deta hai execute karne ke liye. 🧠 In short: Event Loop decide karta hai ki konsa kaam pehle hoga aur konsa baad me. Aur isi wajah se JavaScript asynchronous tasks ko handle kar pata hai. Example:- 1 console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Start End Promise Timeout 💬 Explanation: Even though setTimeout ka delay 0ms hai, Promise (Microtask) always runs first because it has higher priority than Callback Queue. 👍 This was a super interesting topic for me! Every JS developer should understand how the Event Loop works because ye hi control karta hai humare async code ka flow. InshaAllah I’ll keep learning more and share my journey with you all ✨ hashtag#JavaScript#EventLoop#FrontendDevelopment#LearningJourney#WebDevelopment
To view or add a comment, sign in
-
Understanding How JavaScript Manages Memory: Stack, Heap & Garbage Collection As developers, we often use JavaScript every day, but few of us pause to think about how it really manages memory behind the scenes. 🧠 Memory Types: - Stack Memory: Stores primitive data types (like numbers, strings, booleans). These are copied by value — meaning every variable gets its own copy. - Heap Memory: Stores non-primitive data types (like objects, arrays, functions). These are copied by reference — multiple variables can point to the same memory location. 🧹Garbage Collection: JavaScript automatically cleans up unused memory through a process called Garbage Collection, based on the concept of reachability. How It Works Reachability: JS keeps objects in memory if they are reachable (accessible from roots. Unreachable Objects: If an object is no longer referenced, it becomes eligible for garbage collection. Mark-and-Sweep Algorithm: Mark: Identify all reachable objects. Sweep: Delete objects not marked as reachable. Does understanding memory management change the way you write JavaScript? #JavaScript #WebDevelopment #Frontend #MemoryManagement #CodingTips #Developers
To view or add a comment, sign in
-
-
💡 Ever changed a copy of an object… and accidentally changed the original too? If you’ve worked with JavaScript, you know this painful trap all too well! Let’s clarify the difference between shallow copy and deep copy, and see how modern JS handles it. 🔹 Shallow Copy A shallow copy duplicates only the top-level properties. Nested objects or arrays are still shared. const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 → original object changed! ✅ Top-level copied. ⚠️ Nested objects still reference the same memory. 🔹 Deep Copy A deep copy duplicates everything, including nested objects, so changes don’t affect the original. 1️⃣ Using JSON.stringify() + JSON.parse() const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ⚠️ Limitation: Doesn’t handle Dates, Maps, Sets, functions, or circular references. 2️⃣ Using structuredClone() (Modern JS) const original = { name: "Alice", details: { age: 25 } }; const deepCopy = structuredClone(original); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ✅ Handles most types, including Date, Map, Set, etc. ⚠️ Available in modern browsers & Node.js v17+. #JS #JavaScript #WebDevelopment #DeepCopy #ShallowCopy #CodingTips #Programming
To view or add a comment, sign in
-
Today's Topic: Promise Chaining in JavaScript In JavaScript, Promise chaining allows you to execute asynchronous tasks one after another, ensuring that each step waits for the previous one to finish. Instead of nesting callbacks (callback hell ), promises make your code cleaner and easier to maintain. Example: function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 completed ✅"); resolve(10); }, 1000); }); } function step2(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 completed ✅"); resolve(value * 2); }, 1000); }); } function step3(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 completed ✅"); resolve(value + 5); }, 1000); }); } // Promise Chaining step1() .then(result => step2(result)) .then(result => step3(result)) .then(finalResult => console.log("Final Result:", finalResult)) .catch(error => console.error("Error:", error)); ✅ Output (after 3 seconds): Step 1 completed ✅ Step 2 completed ✅ Step 3 completed ✅ Final Result: 25 Each .then() runs after the previous promise resolves — making async flow easy to read and manage. --- 🔖 #JavaScript #WebDevelopment #PromiseChain #AsyncProgramming #CodingTips #FrontendDevelopment #Developers #JSConcepts #CodeLearning #100DaysOfCode #WebDevCommunity
To view or add a comment, sign in
-
-
💡 Quick JavaScript/React Lesson: Don't Mutate State with ++ or -- If you've ever experienced a feature that works perfectly in development but fails silently in production, especially with state logic, mutating operators like ++ and -- might be the hidden culprit. I recently observed a developer struggling with a reducer: ❌ The Buggy Code (Mutation): return { ...state, index: state.index++ }; // The operator -- causes the same issue! This failed after deployment, while the fix below worked: ✅ The Working Code (Immutability): return { ...state, index: state.index + 1 }; // Or, for decrement: state.index - 1 🤔 Why Are Mutating Operators a Silent Killer in React? – The issue is immutability. React and Redux expect state updates to be immutable, meaning they should always return a new object reference. 1️⃣. ++ and -- Mutate: Both the increment (++) and decrement (--) operators are mutating operations. They modify the property's value on the original state object before that original object is returned, allowing it to be spread into the new one. 2️⃣. React Gets Confused: Even though you return a new object ({...state, ...}), the old state reference has been internally modified. React's change detection, which compares the old and new object references, can fail, leading to unpredictable behavior and missed re-renders—a common symptom of production-only bugs. 3️⃣. + and - Create: The simple arithmetic operators (+ and -) are non-mutating. They calculate a new value and set it on the new state object, leaving the original state intact. ⭐️ The Professional Takeaway: – When dealing with state, especially within reducers or useState updates, always use non-mutating methods to compute the new value (e.g., +, -, or functions like slice(), map(), and filter()). Save the powerful, but mutable, operators (++, --, direct assignments) for local function variables. 📢 Stay mindful of mutation; it's often the most subtle bug hiding in plain sight. #ReactJS #JavaScript #WebDevelopment #SoftwareEngineering #Immutability #CodeQuality
To view or add a comment, sign in
-
-
Day 14/100 Day 5 of JavaScript Mastering Loops in JavaScript In JavaScript, loops are used to execute a block of code repeatedly — until a certain condition is met. They help reduce redundancy and make our code more efficient and clean. Let’s understand the main types of loops 🔹 1. for loop Used when you know how many times you want to repeat an action. for (let i = 1; i <= 5; i++) { console.log("Number:", i); } 🧠 Explanation: Here, the loop runs from i = 1 to i = 5. Each time, i increases by 1, printing numbers from 1 to 5. --- 🔹 2. while loop Used when you don’t know how many times the loop should run, but have a condition to check. let i = 1; while (i <= 5) { console.log("Count:", i); i++; } Explanation: This loop keeps running as long as i <= 5. Once i becomes 6, it stops. --- 🔹 3. do...while loop Runs the block at least once, even if the condition is false. let i = 1; do { console.log("Step:", i); i++; } while (i <= 5); --- Why Loops Matter: Avoid repetitive code Handle large datasets efficiently Control complex logic easily --- Pro Tip: Use the right loop for the right situation — for → fixed iterations while → condition-based repetition do...while → execute once before checking condition #10000coders
To view or add a comment, sign in
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
🔥 JavaScript: When “prototype” is NOT an object 👀 We all learn early — > “Every function in JavaScript has a prototype property that is an object.” But JavaScript loves exceptions 😏 Here are some surprising cases where prototype is not an object 👇 RegExp.prototype // → /(?:)/ Array.prototype // → [] Function.prototype // → ƒ () {} Number.prototype // → Number {} String.prototype // → String {} Boolean.prototype // → Boolean {} Symbol.prototype // → Symbol {} BigInt.prototype // → BigInt {} 💡 Notice something? Some of these are functions, arrays, or even regular expressions! That’s because their prototypes are actual instances of their types, not plain objects — so that all instances inherit their core methods directly. For example: Array.prototype.push === [].push // true ✅ RegExp.prototype.test === /abc/.test // true ✅ So next time you assume prototype is always {}, remember — JS is full of living examples 😉 --- 💬 Have you ever found a weird prototype behavior while debugging? Drop it in the comments — let’s break more JS myths together! ⚙️ #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
Demystifying the Prototype in JavaScript If there’s one concept that confuses most developers (even experienced ones), it’s the Prototype. Unlike traditional class-based languages, JavaScript uses prototypal inheritance — meaning objects can inherit directly from other objects. Every JS object has a hidden reference called its prototype, and this is what makes inheritance possible. 🔹 How It Works When you access a property like obj.prop1: 1️⃣ JS first checks if prop1 exists on the object itself. 2️⃣ If not, it looks at the object’s prototype. 3️⃣ If still not found, it continues up the prototype chain until it either finds it or reaches the end. So sometimes a property seems to belong to your object — but it actually lives further down the chain! Example const person = { firstname: "Default", lastname: "Default", getFullName() { return this.firstname + " " + this.lastname; } }; const john = Object.create(person); john.firstname = "John"; john.lastname = "Doe"; console.log(john.getFullName()); // "John Doe" Here’s what happens: JS looks for getFullName on john. Doesn’t find it → checks person (its prototype). Executes the method with this referring to john. Key Takeaways The prototype is just a hidden reference to another object. Properties are looked up the prototype chain until found. The this keyword refers to the object calling the method, not the prototype. Avoid using __proto__ directly — use Object.create() or modern class syntax. One-liner: The prototype chain is how JavaScript lets one object access properties and methods of another — simple, flexible, and core to the language. If you found this helpful, follow me for more bite-sized explanations on JavaScript, React, and modern web development #JavaScript #WebDevelopment #Frontend #React #TypeScript #Coding #LearningInPublic #SoftwareEngineering #TechEducation #WebDevCommunity
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