💡 Most devs think shallow copies always affect the original… but that’s not true! Let’s clear this common JavaScript misconception 👇 🧩 Example 1 — Primitives let obj = { a: 1, b: 2, c: 3 }; let obj2 = { ...obj }; obj2.b++; console.log(obj.b); // 2 ✅ unchanged ➡️ Here b is a primitive (number). Primitives are copied by value, so obj and obj2 have separate copies. Incrementing obj2.b doesn’t affect obj.b. ⚠️ Example 2 — Nested Objects let obj = { a: 1, b: { x: 10 } }; let obj2 = { ...obj }; obj2.b.x = 99; console.log(obj.b.x); // 99 ❗changed ➡️ Here b is an object, and a shallow copy only copies its reference. Both obj.b and obj2.b point to the same memory. So changing one affects the other. 💬 TL;DR Shallow copy doesn’t always affect the original — it depends on what’s inside the object. Primitives → safe Objects → shared #JavaScript #Frontend #WebDevelopment #ReactJS #CodingTips #Programming #JSFacts
JavaScript Shallow Copy Myth Busted
More Relevant Posts
-
JavaScript Concept — “The Power of Closures” 💭 Ever wondered how JavaScript functions “remember” the variables around them? That’s the magic of Closures — one of JavaScript’s most elegant features. Closures allow a function to access variables from its outer scope, even after that scope has closed. This concept powers some of the most powerful patterns in JS — from private variables to event handlers. Here’s a small example 👇 function counter() { let count = 0; return function() { count++; return count; }; } const add = counter(); console.log(add()); // 1 console.log(add()); // 2 It’s simple, elegant, and shows how deep JavaScript really is. #JavaScript #WebDevelopment #Coding #Frontend #Learning
To view or add a comment, sign in
-
Hey, Mates. How are you doing? You know, Even experienced devs trip over JavaScript quirks sometimes — here are a few I’ve seen (and made myself 😅 as well): 1. Using var instead of let or const var is function-scoped and can cause weird bugs due to hoisting. ✅ Use let for variables that change and const for ones that don’t. 2. Forgetting to handle async properly Mixing promises, callbacks, and async/await can lead to race conditions or unhandled rejections. ✅ Always await async functions or chain with .then(), and wrap in try/catch. 3. Comparing values incorrectly == does type coercion (and sometimes weirdly!). ✅ Stick to === for strict comparison. 4. Misunderstanding this Arrow functions don’t have their own this — they inherit from the parent scope. ✅ Know when to use arrow functions vs regular ones. 5. Not handling floating-point math 0.1 + 0.2 !== 0.3 (yes, really). ✅ Use libraries like decimal.js or round your values when precision matters. ⸻ These are small details — but they separate good JavaScript from great JavaScript. 💬 What’s a JS mistake you’ve seen (or made) that taught you something valuable? #JavaScript #WebDevelopment #Programming #CodingTips #Frontend
To view or add a comment, sign in
-
Ever seen a variable live even after its function dies? That’s Closure — the memory ninja of JavaScript 🧠 One of JavaScript’s most powerful (and tricky) features 💡 Let’s look at a simple example 👇 function counter() { let count = 0; return function () { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3 Wait… how does count still remember its value? Didn’t the counter() function finish already? 😅 Here’s the magic 🪄 > A closure allows a function to “remember” the variables from the scope in which it was created — even after that scope is gone. In this example, The inner function still has access to count, Because it closes over the variables from its outer function. That’s why we call it a Closure 🔁 Closures are the reason we can create: ✅ Private variables ✅ Function factories ✅ Modular, memory-efficient code In short — > A closure is how JavaScript gives functions memory 🧠 #JavaScript #Closures #WebDevelopment #Frontend #MERNStack #NodeJS #ReactJS #Coding #SoftwareEngineering #Developers #JSFundamentals
To view or add a comment, sign in
-
How JS Converts [] + {} to [object Object] —🤯 JavaScript can be weirdly magical sometimes. Ever tried this in your console? 👇 [] + {} // Output: "[object Object]" At first glance, it looks confusing — why does an empty array and an empty object become a string? Let’s decode the magic 🪄 1️⃣ + Operator in JS The + operator doesn’t just add numbers — it can also concatenate strings. 2️⃣ Type Conversion Happens! [] (empty array) → when converted to string becomes "" (empty string). {} (empty object) → when converted to string becomes "[object Object]". 3️⃣ Final Expression So JS actually does: "" + "[object Object]" → "[object Object]" ✅ Bonus twist: Try reversing it: {} + [] Now it gives 0 because {} is treated as an empty block,not an object. 🤯 JavaScript — where logic meets magic ✨ 🔹 Follow Prashansa Sinha for more fun JS mysteries and simple explanations 👩💻 #JavaScript #WebDevelopment #Coding #Frontend #JS #LearnToCode #Programming #TechCommunity #Developers #CodeNewbie #WebDev
To view or add a comment, sign in
-
🧠 Understanding Block Statements and Lexical Scope in JavaScript When I first started coding in JavaScript, I didn’t really pay attention to where I declared my variables — as long as the code ran, I was happy 😅. But once I began working on bigger projects, I realized scope and block behavior can make or break your code’s predictability. Here’s the thing: A block statement is simply the part inside { } — it could be inside an if, a for, or even just a standalone block. Example: { let message = "Hello world"; console.log(message); } console.log(message); // ❌ ReferenceError What’s happening? Because of lexical scoping, variables declared with let and const only exist within the block they were defined in. Meanwhile, var ignores that and leaks out — which is one reason modern JS avoids it. Understanding how lexical scope works helps prevent weird bugs and keeps your functions predictable. It’s one of those quiet fundamentals that makes your JavaScript more intentional and less chaotic. Have you ever been bitten by a var variable leaking out of a block before? 😅 #JavaScript #WebDevelopment #Frontend #CleanCode #JSFundamentals
To view or add a comment, sign in
-
-
🚀 JavaScript Gotchas: var vs let in Loops & setTimeout Same code, different output 👇 Ever wondered why this code prints 5 5 5 5 5 instead of 0 1 2 3 4? for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 💡 Reason: var is function-scoped — only one i exists for the entire loop. setTimeout callbacks run after the loop finishes, so each callback sees the final value of i → 5. ✅ Fix it with let: for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } let is block-scoped — each iteration gets a new copy of i. Now, callbacks “remember” the correct value of i. ✅ Output: 0 1 2 3 4 💡 Key takeaway: var → shared variable in loop → tricky in async callbacks let → separate variable per iteration → safer & predictable ✨ Tip: Even setTimeout(..., 0) behaves the same! The event loop always runs callbacks after the current synchronous code. #JavaScript #CodingTips #FrontendDevelopment #WebDevelopment #Programming #LearnJS #DeveloperTips #AsyncJavaScript #Closures
To view or add a comment, sign in
-
-
Those little question marks in JavaScript? They finally make sense now. 😅 💡 Today I learned something subtle but super useful in JavaScript! Those little question marks ? and ?? actually do a lot more than I thought Here’s what clicked for me today ✅ ?? – Nullish Coalescing Operator Returns the right-hand value only if the left-hand side is null or undefined. So it helps you set true defaults without breaking valid falsy values like 0 or "". let count = 0; console.log(count || 10); // 10 (because 0 is falsy) console.log(count ?? 10); // 0 (because 0 is not null/undefined) ✅ || – Logical OR Operator Returns the right-hand side if the left-hand side is falsy (false, 0, "", null, undefined, NaN). It’s great for simple fallbacks - but not when 0 or an empty string are valid values. ✅ ?. – Optional Chaining Safely accesses nested properties without throwing an error. console.log(user?.profile?.email); ✅ ? : – Ternary Operator A clean one-liner for conditions: let age = 20; let status = age >= 18 ? "Adult" : "Minor"; I love how small syntax choices like "?? " vs || can make code both safer and more expressive. Feels like I leveled up my JavaScript brain today 😄 #JavaScript #TodayILearned #WebDevelopment #CodeTips #Frontend
To view or add a comment, sign in
-
🔍 How JavaScript source maps actually work (I never asked…) Today I stumbled upon a great post about JavaScript source maps. We've been using source maps for years… but I never actually stopped to ask myself how the magic works. 📌 TL;DR, Things I didn’t know: 0️⃣ A source map is just a JSON file that maps every chunk of minified code back to the original file, line & column. 1️⃣ The weird mappings string is a compact Base64 + VLQ (variable length quantity, for compressing numbers efficiently) encoding of deltas, not gibberish. 2️⃣ Browsers/devtools decode it instantly, so breakpoints and errors show up in the real code instead of bundle.min.js. 3️⃣ It’s heavily optimized, which is why it’s tiny and fast enough to ship with production bundles. If you ever wondered what’s inside a .map file or how devtools time-travel back to the original code, check this out: 🔗 https://lnkd.in/dhKfX2Vr #javascript #webdev #typescript #frontend #debugging #performance #programming #developers #sourcemaps #webtools
To view or add a comment, sign in
-
-
Today I spent some time understanding Hoisting in JavaScript, and it really helped me see how JS works behind the scenes. Here’s what I learned: 🔹 JavaScript reads the code in two phases: 1️⃣ 𝐌𝐞𝐦𝐨𝐫𝐲 𝐂𝐫𝐞𝐚𝐭𝐢𝐨𝐧 𝐏𝐡𝐚𝐬𝐞 – where variable & function declarations are hoisted 2️⃣ 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐏𝐡𝐚𝐬𝐞 – where the actual code runs 🔹 var is hoisted and set to undefined, so accessing it early doesn’t throw an error. 🔹 let & const are also hoisted but not initialized. They stay in the Temporal Dead Zone, which is why accessing them before the declaration gives a ReferenceError. 🔹 Function declarations are fully hoisted, so they can be called before they are written in the code. Understanding this concept made a lot of things clearer, especially why some errors happen in JS. Learning step by step and enjoying the process! 🚀 #JavaScript #LearningJourney #WebDevelopment #Frontend #Hoisting #10000coders #10kcoders
To view or add a comment, sign in
-
-
⚙ Understanding Functions in JavaScript — The Building Blocks of Code A function in JavaScript is like a mini-program inside your main program. It allows you to reuse code, organize logic, and make your code modular. --- 💡 Definition: A function is a block of code designed to perform a particular task. You can define it once and call it multiple times. --- 🧠 Syntax: function greet(name) { console.log("Hello, " + name + "! 👋"); } greet("Kishore"); greet("Santhiya"); ✅ Output: Hello, Kishore! 👋 Hello, Santhiya! 👋 --- 🧩 Types of Functions: 1. Named Function function add(a, b) { return a + b; } 2. Anonymous Function const multiply = function(a, b) { return a * b; }; 3. Arrow Function const divide = (a, b) => a / b; --- ⚙ Why Functions Matter: ✅ Reusability ✅ Readability ✅ Easier debugging ✅ Cleaner, modular code --- 🔖 #JavaScript #WebDevelopment #FunctionsInJS #Frontend #CodingTips #JSConcepts #LearnToCode #100DaysOfCode #KishoreLearnsJS #DeveloperJourney #WebDevCommunity #CodeLearning
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