🧠 JavaScript Concept: Shallow Copy vs Deep Copy When copying objects in JavaScript, understanding the difference between shallow copy and deep copy is very important. 🔹 Shallow Copy Copies only the top-level properties. Nested objects are still shared by reference. Example: const copy = { ...original }; 🔹 Deep Copy Creates a completely independent copy, including all nested objects. Example: const copy = structuredClone(original); 📌 Key Difference: Shallow Copy → Shares references Deep Copy → Fully independent copy ⚠️ Important: Modifying nested data in a shallow copy will also affect the original object. 📌 Best Practice: Use shallow copy for simple objects and deep copy when working with nested data. #javascript #frontenddevelopment #reactjs #webdevelopment #coding
JavaScript Shallow vs Deep Copy Explained
More Relevant Posts
-
🧠 Day 11 of 21days challenge Shallow vs Deep Copy in JavaScript ⚠️ const copy = { ...obj }; Looks like a copy… but not always safe. Shallow copy duplicates only top-level properties. Deep copy creates a completely independent object. For easy understanding :- Shallow copy = shared nested reference Deep copy = fully independent copy Shallow changes affect original 👉 That’s why bugs happen in state updates This changed how I handle object mutations 🚀 #JavaScript #Frontend #InterviewPrep
To view or add a comment, sign in
-
-
Something small but nice I recently came across in JavaScript 👨💻✨ : String.trimEnd(). Earlier, whenever I needed to remove only the trailing spaces from a string, I used to write a small regex for it or sometimes even used .trim(). But .trim() removes both leading and trailing spaces, which isn’t always what we want — especially when the leading indentation actually matters. For example, I used to do something like this: const message = " Action Required: Clear Cache "; // Earlier approach const cleaned = message.replace(/\s+$/, ""); It works, but the regex isn’t exactly the most readable thing 🤯. Recently I noticed there’s a much cleaner native way 👇 const message = " Action Required: Clear Cache "; const result = message.trimEnd(); Now it clearly expresses the intent: remove only the trailing whitespace while keeping the start intact ✅. Result: " Action Required: Clear Cache" Small things like this make code more readable and intentional ✨, and since it’s part of modern JavaScript (along with trimStart()), there’s no need for regex hacks anymore. Sometimes the language already has the cleaner solution, we just discover it a bit later 😄🚀 #JavaScript #CodingTips #CleanCode #WebDev #WebDevelopment
To view or add a comment, sign in
-
🚀 Day 10 of My JavaScript Journey ✨Today I explored how JavaScript actually works behind the scenes — and honestly, it changed the way I look at code completely 🤯 Here’s what I learned 👇 🧠 How JavaScript Code RunsJavaScript doesn’t just execute line by line — it first creates an Execution Context which manages everything. ⚙️ Execution Context Phases1️⃣ Memory Allocation Phase Variables get stored with undefined Functions are stored completely 2️⃣ Execution Phase Code runs line by line Values get assigned and functions execute 📦 Call Stack & Execution Flow JavaScript uses a Call Stack to manage function calls Each function creates its own execution context Stack follows LIFO (Last In, First Out) 💾 Stack vs Heap Memory Stack → Stores primitive values (fast ⚡) Heap → Stores objects (reference-based 🧩) 🤖 Interpreter BehaviorJavaScript reads and executes code step by step using an interpreter — not compiled like some other languages. ❓ Why undefined Appears?Because during memory phase, variables are declared but not initialized yet. ⬆️ Hoisting Explained var is hoisted with undefined Functions are fully hoisted let & const are hoisted but stay in Temporal Dead Zone (TDZ) ❌ 🚫 Temporal Dead Zone (TDZ)You can’t access let & const variables before initialization — it throws an error. ⚠️ Function Expressions vs Hoisting Function declarations → hoisted ✅ Function expressions → behave like variables ❌ 💡 Key TakeawayUnderstanding execution context, memory, and hoisting makes debugging WAY easier and helps write cleaner code 🔥 📌 Slowly moving from writing code → to understanding how it actually works inside #JavaScript #WebDevelopment #MERNStack #CodingJourney #LearnToCode #FrontendDevelopment #DeveloperLife
To view or add a comment, sign in
-
-
⚡ Promises vs Async/Await in JavaScript (Simple Explanation) When working with asynchronous JavaScript, I used to get confused between Promises and async/await. Over time, I realized they are closely related — just different ways of handling async code. Here’s a simple breakdown 👇 🔹 Promises A Promise represents a value that will be available in the future. Example: fetchData() .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); It works well, but chaining multiple .then() calls can sometimes reduce readability. 🔹 Async/Await async/await is built on top of Promises and makes code look more synchronous and cleaner. Example: async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error(error); } } 🔹 Key Difference Promises → chaining (.then()) Async/Await → cleaner, easier to read 🔹 When to use what? ✅ Use async/await for most modern applications ✅ Use Promises when working with parallel operations (like Promise.all) 💡 One thing I’ve learned: Understanding async JavaScript deeply makes debugging and building real-world applications much easier. Curious to hear from other developers 👇 Do you prefer Promises or async/await in your projects? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🚀 JavaScript Concepts Series – Day 9 / 30 📌 Promises & Async/Await in JavaScript 👀 Let's Revise the Basics 🧐 Understanding Promises & Async/Await is key to handling asynchronous operations cleanly and efficiently. They help you write non-blocking code without callback hell. 🔹 Promises A Promise represents a value that may be available now, later, or never States: Pending → Resolved → Rejected const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done"), 1000); }); promise.then(res => console.log(res)) .catch(err => console.log(err)); 🔹 Async/Await Syntactic sugar over promises Makes async code look like synchronous code async function fetchData() { try { const res = await promise; console.log(res); } catch (err) { console.log(err); } } 🔹 Why Use It? Cleaner and readable code Better error handling with try...catch Avoids callback hell 💡 Key Insight Promise → Handles async operations async/await → Makes it readable await → Pauses execution (non-blocking) Mastering this helps you work with APIs, handle data, and build real-world applications efficiently. More JavaScript concepts coming soon. 🚀 #javascript #js #webdevelopment #frontenddeveloper #coding #programming #developers #softwaredeveloper #learnjavascript #javascriptdeveloper #codinglife #devcommunity #webdev #reactjs #mernstack #codingjourney #codeeveryday #developerlife #100daysofcode #techlearning #asyncjs #promises
To view or add a comment, sign in
-
-
I was recently asked a classic JavaScript "gotcha" in an interview: "How do you return an object in an arrow function, and why are parentheses required?" It sounds simple But the "Why" is where most developers get tripped up. The Problem: In JavaScript, {} is ambiguous. It can mean an Object Literal OR a Function Block. By default, the JS engine sees a brace after an arrow => and assumes it's a function block. The Result: const getUser = () => { name: 'Chandhan' }; The engine thinks name: is a label and returns undefined. The Fix: Wrap it in parentheses! ({ ... }) The () forces the engine to treat the contents as an expression, not a statement. ✅ const getUser = () => ({ name: 'Chandhan' }); Small syntax, big difference in how the engine parses your code. #JavaScript #WebDevelopment #CodingTips #Angular #Frontend #InterviewPrep
To view or add a comment, sign in
-
🚀 JavaScript String Optimization You Probably Didn’t Know When you build strings in a loop like this: let bigString = ""; for (let i = 0; i < 1000; i++) { bigString += "chunk" + i; } It looks expensive… but surprisingly, it’s not (at first). 👉 JavaScript engines are smart. Instead of immediately creating a new string every time, they use something called a ConsString (concatenated string) — a lazy structure that avoids copying data. ⚡ This means: String building stays fast and memory-efficient No actual concatenation happens yet But here’s the catch… 💥 The moment you try to access the string (like bigString[0]), JavaScript materializes it — flattening everything into a real string, which can be expensive. 📌 Key Insight: Building strings → cheap Accessing/manipulating them → can trigger hidden cost 💡 Takeaway: Performance isn’t just about what you write — it’s about when the engine does the heavy work. #JavaScript #WebPerformance #CleanCode #Programming #FrontendDevelopment #DevTips #reactjs #webdevelopment
To view or add a comment, sign in
-
-
Shallow Copy vs Deep Copy — JavaScript Developers Must Know! When working with objects in JavaScript, understanding the difference between shallow copy and deep copy is crucial 🔸 Shallow Copy Creates a copy of the object, but nested objects are still shared. Changing nested values will affect the original object. 🔸 Deep Copy Creates a completely independent copy. Changes won’t impact the original object at all. 💡 In short: - Shallow Copy = ⚠️ Shared references - Deep Copy = ✅ Fully independent 📌 Pro Tip: Use "structuredClone()" for reliable deep copying in modern JavaScript. Understanding this concept can save you from unexpected bugs and make your code more predictable #JavaScript #WebDevelopment #CodingTips #Frontend #Developers #Programming
To view or add a comment, sign in
-
-
🚀 Day 5 — Understanding JavaScript Hoisting & Execution Context Missed sharing yesterday’s update, so posting it today 👇 Continuing my journey of strengthening core JavaScript fundamentals, I explored one of the most important (and commonly asked) concepts in interviews — how JavaScript actually runs behind the scenes. 🔹 Covered topics: - JavaScript Hoisting: • Variables and functions can be used before declaration • Only declarations are hoisted, not initializations • Difference in behavior: var vs let vs const - Temporal Dead Zone (TDZ): • Why let & const throw errors before initialization • Understanding “Cannot access before initialization” - Execution Context (🔥 very important): • How JavaScript executes code internally • Two phases: - Memory Creation Phase - Execution Phase - Memory Creation Phase: • Variables stored as undefined • Functions stored completely - Execution Phase: • Code runs line by line • Values get assigned and functions executed - Function Hoisting: • Function declarations are fully hoisted • Function expressions behave differently - Call Stack: • How JavaScript manages function execution (LIFO) 💡 Key Learning: JavaScript is not executing code line-by-line directly — it first scans and prepares memory, then executes. 👉 Concepts like: - Why var gives undefined but let/const throw error - How execution context is created - How functions are stored and executed - What happens internally before a single line runs These are core interview concepts that define how deeply you understand JavaScript. This phase is helping me move from just writing code → to understanding how JavaScript engine actually works internally ⚡ 📌 Day 5 of consistent preparation — building strong fundamentals step by step 🔥 #JavaScript #WebDevelopment #FullStackDeveloper #CodingJourney #MERNStack #InterviewPreparation #Frontend #Backend #LearnInPublic #Developers #LinkedIn #Consistency #Connections
To view or add a comment, sign in
-
Day 3: Hoisting — The JavaScript "Magic" That Isn't Magic at All! 🎩✨ Today, I tackled one of the most famous (and often misunderstood) concepts in JavaScript: Hoisting. If you've ever wondered why you can call a function before you even define it in your code, you've witnessed Hoisting in action! 🤔 What is Hoisting? Hoisting is a mechanism where variables and function declarations are moved to the top of their containing scope during the Memory Allocation Phase, before the code even starts executing. 🔍 Under the Hood (The Execution Context) Remember the "Big Box" (Execution Context) from Day 1? Here is what happens during the Memory Phase: Variables (var): JS allocates memory for variables and initializes them with a special value: undefined. Functions: JS stores the entire function body in memory. This is why: Calling a function at Line 1 works perfectly! ✅ Accessing a var at Line 1 returns undefined instead of an error! ⚠️ 💻 The Browser Demo (The Call Stack) Watching this live in the Sources tab of Chrome DevTools was a game-changer. Seeing the Global scope populate with variables before the first line of code executed made everything click. 💡 Interview Tip: When asked "What is Hoisting?", don't just say "it moves code to the top." Better Answer: "Hoisting is the process where the JS Engine allocates memory for variables and functions during the Creation Phase of the Execution Context. This allows us to access functions and variables even before they are initialized in the code, though var will return undefined until the execution reaches its assignment." Next up: Diving into how let and const handle hoisting differently (The Temporal Dead Zone!). Are you a var, let, or const person? Let's discuss below! 👇 #JavaScript #WebDevelopment #Hoisting #NamasteJavaScript #CodingInterviews #FrontendEngineer #ProgrammingLogic #JSFundamentals
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