⚡ SK – Deep vs Shallow Copy in JavaScript: Avoid Hidden Bugs! 💡 Explanation (Clear + Concise) Copying objects or arrays might look simple — but if you’re not careful, you’ll end up mutating your original data. That’s the difference between shallow copy and deep copy. 🧩 Real-World Example (Code Snippet) const user = { name: "Sasi", address: { city: "Chennai" } }; // 🧩 Shallow Copy (one level only) const shallowCopy = { ...user }; shallowCopy.address.city = "Bangalore"; console.log(user.address.city); // ⚠️ Affected! → "Bangalore" // 🧠 Deep Copy const deepCopy = JSON.parse(JSON.stringify(user)); deepCopy.address.city = "Coimbatore"; console.log(user.address.city); // ✅ "Bangalore" console.log(deepCopy.address.city); // ✅ "Coimbatore" ✅ Why It Matters in React: Prevents unwanted state mutations in components or Redux. Ensures immutability — a key principle in React state management. Avoids re-rendering bugs and hard-to-track side effects. 💬 Question: Have you ever faced a bug because of shallow copying in React state updates? 📌 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 #DeepCopy #ShallowCopy #FrontendDeveloper #CodingJourney #StateManagement #JSFundamentals
"Shallow vs Deep Copy in JavaScript: Avoid Bugs"
More Relevant Posts
-
🔗 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
-
-
🔐 Closures in JavaScript — The Hidden Superpower Closures make JavaScript truly powerful — they allow functions to remember variables even after the outer function has finished execution 🔥. 🎯 Real-World Uses of Closures ✅ Data privacy → hide sensitive variables ✅ Stateful logic → counters, caching, sessions ✅ Functional programming → currying, memoization ✅ Async tasks → setTimeout, promises, event handlers ✅ Module pattern → private scope, public API ⚠️ Watch out for Memory leaks (large objects in closures) var inside loops (same reference for all callbacks) Stale Closures in React Hooks. ✅ Key Takeaway 🔥 Closure = Function + Remembered Lexical Scope 📍 For the full detailed article, check here: https://lnkd.in/eCjZANPj #javascript #frontend #webdevelopment #programming #interviewprep #codingtips #developers #closures #react
To view or add a comment, sign in
-
⚡ SK – Mastering Array Methods: map(), filter(), reduce(), and find() in JavaScript 💡 Explanation (Clear + Concise) Array methods are the power tools of JavaScript — they make data transformation cleaner, functional, and readable. As a React developer, you use them daily — to render lists, filter data, and compute state. 🧩 Real-World Example (Code Snippet) const products = [ { name: "Laptop", price: 1000 }, { name: "Phone", price: 600 }, { name: "Tablet", price: 400 }, ]; // 🗺️ map() – transform data const productNames = products.map(p => p.name); // 🔍 filter() – select matching items const affordable = products.filter(p => p.price < 800); // ➕ reduce() – compute totals const totalPrice = products.reduce((sum, p) => sum + p.price, 0); // 🧭 find() – get first matching item const phone = products.find(p => p.name === "Phone"); console.log(productNames, affordable, totalPrice, phone); ✅ Why It Matters in React: map() is used to render lists dynamically filter() helps with search or category filtering reduce() is great for analytics (total revenue, cart total, etc.) 💬 Question: Which array method do you use most 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 #FrontendDeveloper #ArrayMethods #CodingJourney #WebDevelopment #JSFundamentals #CareerGrowth #map #filter #reduce
To view or add a comment, sign in
-
-
🚀 Deep Clone an Object in JavaScript (without using JSON methods!) Ever tried cloning an object with const clone = JSON.parse(JSON.stringify(obj)); and realized it breaks when you have functions, Dates, Maps, or undefined values? 😬 Let’s learn how to deep clone an object the right way - without relying on JSON methods. What’s the problem with JSON.parse(JSON.stringify())? t’s a quick trick, but it: ❌ Removes functions ❌ Converts Date objects to strings ❌ Skips undefined, Infinity, and NaN ❌ Fails for Map, Set, or circular references So, what’s the alternative? ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). structuredClone() handles Dates, Maps, Sets, and circular references like a champ! structuredClone() can successfully clone objects with circular references (where an object directly or indirectly references itself), preventing the TypeError: Converting circular structure to JSON that occurs with JSON.stringify(). ✅ Option 2: Write your own recursive deep clone For learning purposes or environments without structuredClone(). ⚡ Pro Tip: If you’re working with complex data structures (like nested Maps, Sets, or circular references), use: structuredClone() It’s native, fast, and safe. Final Thoughts Deep cloning is one of those "simple but tricky" JavaScript topics. Knowing when and how to do it properly will save you hours of debugging in real-world projects. 🔥 If you found this helpful, 👉 Follow me for more JavaScript deep dives - made simple for developers. Let’s grow together 🚀 #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #AkshayPai #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
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
-
-
⚙️ Writing Intentional JavaScript — Beyond the Syntax A mark of an experienced engineer is not just knowing what works, but why it behaves that way and when that behavior aligns with your intent. JavaScript’s flexibility is both a gift and a risk. The same expression can look simple yet carry subtle logic flows that aren’t immediately obvious. 🧩 Example 1: Understanding short-circuit evaluation const username = isReady && user.name || "Guest"; At a glance, many developers read this as: “If isReady is true, show user.name, otherwise show 'Guest'.” But that’s not how JavaScript evaluates it. Let’s unpack it: • The && operator has higher precedence than ||. • So the expression is grouped as: (isReady && user.name) || "Guest" • This means: • If isReady is falsy, the left side of && stops immediately → false || "Guest" → "Guest". • If isReady is truthy, it moves on to check user.name. • If user.name is also truthy, you get that value. • If user.name is falsy (like "", 0, or null), it still falls back to "Guest". So even though isReady is true, "Guest" may still print — which surprises many engineers who assume the first truthy condition guarantees the result. ✅ A clearer alternative when clarity is more valuable than brevity: const username = (isReady && user.name) ?? "Guest"; Or if need to check for falsy value then const username = (isReady && user.name) || "Guest"; The key isn’t to avoid these patterns, but to use them consciously, understanding their evaluation flow. 🧩 Example 2: The return-line break function getData() { return { name: "Aamir" } } This function returns undefined. Because of Automatic Semicolon Insertion (ASI), JavaScript interprets it as: return; { name: "Aamir" } ✅ Always return the object on the same line: function getData() { return { name: "Aamir" } } 🧠 The larger point JavaScript isn’t unpredictable — it’s precise. When we misread its operator precedence or parsing rules, we invite subtle bugs that the compiler won’t catch. As systems scale, understanding how the language evaluates expressions becomes more valuable than memorizing syntax patterns. That’s how we move from “it works” to “it’s intentional.” #JavaScript #EngineeringLeadership #TypeScript #SoftwareCraftsmanship #FrontendEngineering
To view or add a comment, sign in
-
🚀 New Blog Alert! Ever changed a nested value in JavaScript and wondered why your original object also changed? 😅 That’s the hidden magic (and pain) behind shallow vs deep copy in JavaScript. In my latest Medium article, I’ve broken down: 🧠 How JavaScript handles memory (stack vs heap) 🔍 Why shallow copies share references ⚙️ How deep copy truly works under the hood 💡 Real-world examples using structuredClone(), Object.assign(), and lodash.cloneDeep() 👉 Read here: https://lnkd.in/d9VdByK6 #JavaScript #WebDevelopment #Coding #DeepCopy #ShallowCopy #Frontend #MERN #ShubhamDeveloper
To view or add a comment, sign in
-
JavaScript learn 1. typeof NaN → "number" Even though NaN means “Not-a-Number”, JavaScript treats it as a number type. So typeof NaN returns "number". 2. 9999999999999999 → 10000000000000000 JavaScript uses 64-bit floating point numbers, which cannot precisely represent very large integers. 9999999999999999 gets rounded to 10000000000000000. 3. 0.5 + 0.1 == 0.6 → true This combination is precisely representable in floating point math, so it evaluates correctly. 4. 0.1 + 0.2 == 0.3 → false Floating-point precision error. 0.1 + 0.2 actually equals: 0.30000000000000004 So it is not equal to 0.3. 5. Math.max() → -Infinity With no arguments, JavaScript treats the max value as the smallest possible value: -Infinity. 6. Math.min() → Infinity With no arguments, JavaScript treats min value as the largest possible value: Infinity. 7. [] + [] → "" Both arrays convert to empty strings during concatenation: "" + "" = "". 8. [] + {} → "[object Object]" [] becomes "" {} becomes "[object Object]" Result: "" + "[object Object]". 9. {} + [] → 0 JavaScript interprets {} as an empty block, not an object. Then it converts [] to a number → 0. 10. true + true + true === 3 → true Boolean → Number conversion: true → 1 1 + 1 + 1 = 3. 11. true - true → 0 Boolean converted again: 1 - 1 = 0. 12. true == 1 → true Loose equality (==) performs type coercion: true → 1 → so 1 == 1. 13. true === 1 → false Strict equality (===) does not convert types. Boolean is not equal to number.
To view or add a comment, sign in
-
⚡ SK – Destructuring & Spread/Rest Operators: Simplifying Your JavaScript Code 💡 Explanation (Clear + Concise) Destructuring and spread/rest operators make your JavaScript code cleaner, shorter, and more readable — by unpacking or combining data from arrays and objects efficiently. 🧩 Real-World Example (Code Snippet) // 🧱 Object Destructuring const user = { name: "Sasi", role: "React Developer", city: "Chennai" }; const { name, role } = user; console.log(`${name} works as a ${role}`); // Sasi works as a React Developer // 🔁 Array Destructuring const skills = ["React", "Redux", "TypeScript"]; const [primarySkill, , extraSkill] = skills; console.log(primarySkill, extraSkill); // React TypeScript // 🚀 Spread Operator (copy or merge) const devDetails = { ...user, country: "India" }; // 🧩 Rest Operator (group remaining) const { city, ...profile } = user; console.log(profile); // { name: 'Sasi', role: 'React Developer' } ✅ Why It Matters in React: Extract props and state easily: const { title, price } = product; Pass data without mutating: setUser({ ...user, loggedIn: true }); 💬 Question: What’s one place in your recent React project where destructuring made your code cleaner? 📌 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 #FrontendDeveloper #CodingJourney #WebDevelopment #JSFundamentals #TechLearning #CareerGrowth #CodeTips
To view or add a comment, sign in
-
-
🚀 Understanding the "Single Number" Problem (LeetCode 136) In JavaScript, there’s always something new to discover — even in simple-looking problems. Recently, I revisited the Single Number challenge and explored two different approaches: using a hash table and using XOR. 💡 Approach 1: Using a Hash Table We create an object that counts how many times each number appears. If a number appears once, that’s our answer. function singleNumber(arr) { let hash = {}; // frequency map for (let i = 0; i < arr.length; i++) { if (!hash[arr[i]]) hash[arr[i]] = 1; else hash[arr[i]]++; } for (let i = 0; i < arr.length; i++) { if (hash[arr[i]] === 1) return arr[i]; } } console.log(singleNumber([2, 2, 1])); // Output: 1 ⚡ Approach 2: Using XOR (bitwise logic) This approach is faster — duplicate numbers cancel each other out, leaving only the single one. function singleNumber(arr) { let xor = 0; for (let i = 0; i < arr.length; i++) { xor = xor ^ arr[i]; } return xor; } console.log(singleNumber([4, 1, 2, 1, 2])); // Output: 4 The XOR trick is elegant . 🧠 Quick Concepts 🔸 Hash Table (Object in JS): Think of it like a locker with labels — each label (key) stores a value. You can easily count or find things using those keys. Example: let hash = {}; hash["apple"] = 2; // apple appears twice 🔸 XOR (Exclusive OR): It’s a bitwise operation that gives: 1 if bits are different 0 if bits are same 👉 Same numbers cancel out: 2 ^ 2 ^ 1 = 1 That’s why XOR is a shortcut for finding the unique number! 🎯 Takeaway: Even a small problem can teach you how counting works in objects and how bitwise logic simplifies code. Learning by doing builds real understanding 💪 #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing
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