Day 48/50 – JavaScript Interview Question? Question: What is the difference between shallow copy and deep copy? How do you implement each? Simple Answer: Shallow copy duplicates top-level structure but keeps references to nested objects. Deep copy recursively duplicates all nested objects. Shallow: spread operator, Object.assign(). Deep: structuredClone(), JSON.parse(JSON.stringify()), or custom recursion. 🧠 Why it matters in real projects: Wrong copy method causes bugs in state management (React/Redux), data manipulation, and form handling. Shallow copies are fast but dangerous with nested data. Deep copies prevent mutations but can be expensive. 💡 One common mistake: Using spread operator for nested objects expecting deep copy. Mutations affect the original! Also using JSON.parse(JSON.stringify()) which fails for functions, dates, undefined, and circular references. 📌 Bonus: const original = { name: 'Alice', address: { city: 'NYC' }, hobbies: ['reading'] }; // Shallow copy - nested objects still shared const shallow = { ...original }; shallow.address.city = 'LA'; console.log(original.address.city); // 'LA' - Oops! // Deep copy - Modern way (best!) const deep = structuredClone(original); deep.address.city = 'Boston'; console.log(original.address.city); // 'NYC' - ✓ Independent! // JSON method (has limitations) const deep2 = JSON.parse(JSON.stringify(original)); // ✗ Loses functions const obj = { fn: () => {} }; JSON.parse(JSON.stringify(obj)); // {} - lost! // ✗ Breaks dates const obj2 = { date: new Date() }; JSON.parse(JSON.stringify(obj2)); // date becomes string! // Custom deep clone (interview favorite) function deepClone(obj, hash = new WeakMap()) { if (obj === null || typeof obj !== 'object') return obj; if (hash.has(obj)) return hash.get(obj); // Circular ref if (obj instanceof Date) return new Date(obj); if (Array.isArray(obj)) { const arr = []; hash.set(obj, arr); obj.forEach((item, i) => arr[i] = deepClone(item, hash)); return arr; } const copy = {}; hash.set(obj, copy); Object.keys(obj).forEach(key => { copy[key] = deepClone(obj[key], hash); }); return copy; } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
JavaScript Interview Question: Shallow vs Deep Copy
More Relevant Posts
-
🚨 JavaScript Interview Trap: Shallow Copy vs Deep Copy Many developers think they understand object copying… Until this bug appears in production. 😅 You copy an object. You modify the copy. And suddenly… 💥 The original object also changes. Why does this happen? Because in JavaScript, objects are stored by reference. 🧠 Example JavaScript const user = { name: "Sajid", skills: ["JavaScript", "React"] }; const copy = { ...user }; copy.skills.push("Node.js"); console.log(user.skills); // ["JavaScript", "React", "Node.js"] Even though we copied the object… the original data changed. ⚠️ What Happened? This was a Shallow Copy. A shallow copy only duplicates the first level of an object. Nested objects or arrays still share the same memory reference. Think of it like: 📦 New box 📦 Same items inside Common Shallow Copy Methods These do NOT create deep copies: • Spread Operator { ...obj } • Object.assign() • Array.slice() • Array.from() They work great for flat objects. But for nested data, they can cause hidden bugs. 💡 Solution: Deep Copy To fully duplicate nested data: JavaScript const deepCopy = structuredClone(user); or JavaScript const deepCopy = JSON.parse(JSON.stringify(user)); Now changes won't affect the original object. ⚡ Small JavaScript concepts like this cause huge production bugs. Most developers learn syntax. Great developers understand how memory actually works. 💬 Quick question for you: Have you ever faced a Shallow Copy bug in a project? Comment "YES" or "NEVER AGAIN" 😄
To view or add a comment, sign in
-
Hash Maps: The Swiss Army Knife of Coding Interviews (When to Reach for Them and Why) Imagine this: The problem asks you to find duplicates, count frequencies, or check if two arrays have the same elements. You could nest loops and get O(n²). Or you could throw everything into a hash map (or set) and get O(n) time with O(n) space. In coding interviews, the hash map is the structure that turns "check if we've seen this" and "how many of each?" into one pass. It's the Swiss Army knife: not always the most elegant, but when the problem has "find," "count," "group," or "seen before," it's usually the first thing to reach for. When to use it: When you need O(1) lookup, insert, or delete by key. When you need to count occurrences (frequency map). When you need to group elements by some property. When you need to remember what you've seen (two sum, duplicates, subarray with sum k). The pattern is often: one pass, put elements (or their indices or counts) in the map, and use the map to answer the question in the same pass or a second pass. In system design, the same idea shows up as caches and key-value stores—hash-based distribution, constant-time access. Why it matters in interviews: They're testing whether you know your data structures and when to trade space for time. Saying "I'll use a hash map to store the counts" or "I'll use a set to track seen elements" signals you know the toolkit. The trap is overusing it when a simpler structure works (e.g. array for small fixed range, two pointers for sorted arrays) or when the problem has ordering constraints that a plain hash map doesn't preserve. In those cases you might need a different structure (e.g. linked list + map for LRU, or a tree). But for "have we seen this?" and "how many?" the hash map is the default. The fix is to recognize the cues: need to look up by value, need to count, need to group, need to detect duplicates or pairs. Then choose key and value (element → count, element → index, etc.) and implement. Know the language: in JavaScript it's Map or object; in Python, dict; in Java, HashMap. And know the tradeoff: O(n) space. If the problem has a small range (e.g. lowercase letters), an array of size 26 might be better. Otherwise, hash map. Hash maps are like that friend who remembers everyone's name at the party—you pay for the drink (space), and in return you get the answer in one lookup. Pro tip: Practice Two Sum, Group Anagrams, and Longest Substring Without Repeating Characters. All three lean on a map or set. Once you see the pattern, you'll reach for it automatically. What's the first problem where a hash map "clicked" for you? Share below.
To view or add a comment, sign in
-
JavaScript Interview Question #2 ------------------------------------ Problem: Convert an array of key-value objects into a single object. Input: [{"key": "a", "value":1}, {"key": "b", "value": 2}] Output: {"a" : 1, "b" : 2} Solution: The input is an array of objects, and the goal is to transform it into a single object. There are multiple ways to solve this: 1. using for...of loop const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; let newObj = {}; for(let e of arr){ newObj[e.key] = e.value; } console.log(newObj); 2. using Object.fromEntries const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = Object.fromEntries( arr.map(item => [item.key, item.value]) ); console.log(newObj); 3. using reduce() const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = arr.reduce((acc, curr) => { acc[curr.key] = curr.value; return acc; }, {}); console.log(newObj); ------------------------------------------------------------------------------------- Different approaches help to build flexibility in problem-solving. I used the for...of loop in my interview. Which one do you prefer ?
To view or add a comment, sign in
-
-
Day 49/50 – JavaScript Interview Question? Question: What is the difference between stopPropagation(), stopImmediatePropagation(), and preventDefault()? Simple Answer: stopPropagation() prevents event from bubbling/capturing to other elements. stopImmediatePropagation() also prevents other handlers on current element. preventDefault() cancels default browser action but doesn't stop propagation. 🧠 Why it matters in real projects: These control event behavior in complex UIs with nested elements. Misusing them causes bugs like forms not submitting, clicks triggering parent handlers, or custom behavior failing. Critical for proper event handling. 💡 One common mistake: Using stopPropagation() everywhere "to be safe" breaks event delegation patterns. Also confusing preventDefault() with stopping propagation—they serve different purposes. 📌 Bonus: // HTML: <div id="outer"><button id="inner">Click</button></div> const outer = document.getElementById('outer'); const inner = document.getElementById('inner'); // stopPropagation() - stops event flow inner.addEventListener('click', (e) => { console.log('Inner'); e.stopPropagation(); // Stops here! }); outer.addEventListener('click', () => { console.log('Outer'); // Won't fire }); // stopImmediatePropagation() - stops all handlers inner.addEventListener('click', (e) => { console.log('Handler 1'); e.stopImmediatePropagation(); }); inner.addEventListener('click', () => { console.log('Handler 2'); // Won't fire! }); // preventDefault() - cancels default action const link = document.querySelector('a'); link.addEventListener('click', (e) => { e.preventDefault(); // Link won't navigate // Event still propagates to parent! }); const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // Form won't submit handleAjaxSubmit(new FormData(form)); }); // Practical: Modal overlay modal.addEventListener('click', (e) => { e.stopPropagation(); // Clicks on modal don't close it }); overlay.addEventListener('click', () => { closeModal(); // Clicks on overlay close it }); // Best practice: Don't break delegation document.querySelector('.list').addEventListener('click', (e) => { if (e.target.matches('.item')) { // Don't use stopPropagation here! handleItemClick(e.target); } }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Events #EventPropagation #WebDev #DOM
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming *Double Tap ❤️ For More*
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming
To view or add a comment, sign in
-
Day 50/50 – JavaScript Interview Question? Question: What is the difference between setTimeout(), setImmediate(), and process.nextTick() in Node.js? Simple Answer: setTimeout() schedules callback in macrotask queue after delay. setImmediate() executes in next event loop iteration. process.nextTick() executes before next phase (microtask, highest priority). Order: nextTick() → Promises → setImmediate() → setTimeout(). 🧠 Why it matters in real projects: Understanding these is crucial for Node.js performance, avoiding event loop starvation, and controlling async execution order. Misusing them causes performance bottlenecks or unexpected behavior. 💡 One common mistake: Overusing process.nextTick() starves the event loop since it runs before I/O. Also assuming setImmediate() runs immediately—it's actually next iteration, and order with setTimeout(0) can vary. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: setTimeout'), 0); setImmediate(() => console.log('3: setImmediate')); process.nextTick(() => console.log('4: nextTick')); Promise.resolve().then(() => console.log('5: Promise')); console.log('6: End'); // Output: // 1: Start // 6: End // 4: nextTick (highest priority) // 5: Promise (microtask) // 3: setImmediate (next loop) // 2: setTimeout (timer phase) // Use cases: // nextTick - let constructor complete class AsyncResource { constructor() { process.nextTick(() => this.init()); } } // setImmediate - break up long operations function processLargeArray(arr) { const chunk = arr.splice(0, 100); processChunk(chunk); if (arr.length > 0) { setImmediate(() => processLargeArray(arr)); // ✓ Yields } } // Danger: Recursive nextTick starves I/O! function dangerous() { process.nextTick(dangerous); // ✗ Infinite, blocks I/O } // Better: use setImmediate for recursion function better() { setImmediate(better); // ✓ Allows I/O } // Modern alternative to nextTick Promise.resolve().then(() => { // Microtask like nextTick, less aggressive }); 🎉 Series Complete! 50/50 JavaScript Interview Questions #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #NodeJS #EventLoop #AsyncProgramming #WebDev #SeriesComplete
To view or add a comment, sign in
-
🚀 Why the "+" Operator Works Differently in JavaScript In JavaScript, arithmetic operators like "+", "-", "*", "/", and "%" are used to perform mathematical operations. However, the "+" operator is special because it can perform two different tasks: 1️⃣ Arithmetic Addition 2️⃣ String Concatenation Let’s understand why this happens. --- 1️⃣ "+" as an Arithmetic Operator When both values are numbers, the "+" operator performs normal addition. Example let a = 10; let b = 5; console.log(a + b); // 15 Here JavaScript clearly sees two numbers, so it performs arithmetic addition. --- 2️⃣ "+" as a Concatenation Operator When one of the values is a string, JavaScript converts the other value to a string and joins them together. This is called string concatenation. Example let text = "Age: "; let age = 25; console.log(text + age); // Age: 25 Here JavaScript converts "25" into a string and joins it with ""Age: "". --- 3️⃣ Why Other Operators Don’t Concatenate Other arithmetic operators like "-", "*", "/", "%" only perform mathematical operations. They do not support string concatenation. Example: console.log("10" - 5); // 5 JavaScript converts ""10"" into a number and performs subtraction. Another example: console.log("10" * 2); // 20 Here ""10"" is converted into a number before multiplication. --- 4️⃣ When Does This Behavior Happen? This behavior happens because of type coercion in JavaScript. JavaScript automatically converts values depending on the operator being used. - If "+" sees a string, it converts everything to string and concatenates. - Other operators convert values to numbers and perform arithmetic operations. Example: console.log(5 + "5"); // "55" console.log(5 - "5"); // 0 --- ✅ Key Takeaway - "+" → Can perform addition and string concatenation - "-", "*", "/", "%" → Always perform numeric operations 💡 Because of JavaScript’s type coercion, the "+" operator behaves differently compared to other arithmetic operators. Understanding this concept helps you avoid unexpected results in JavaScript. #JavaScript #WebDevelopment #Programming #BackendDevelopment #LearnToCode
To view or add a comment, sign in
-
🤔 Ever copied an object with { ...obj } and thought you made a fully separate copy… then a nested value changed in both places? That’s the shallow vs deep copy trap in JavaScript. 🧠 JavaScript interview question What’s the difference between a shallow copy and a deep copy in JavaScript? ✅ Short answer A shallow copy copies only the top-level properties. If a property contains a nested object or array, the copy still points to the same reference. A deep copy creates a fully independent clone, including nested objects and arrays. 🔍 A bit more detail Shallow copy Top-level values are copied Nested objects/arrays are still shared Changing nested data affects both the original and the copy Common shallow copy methods: spread syntax: { ...obj } Object.assign() array methods like slice() and concat() Deep copy Clones nested structures too Changes in the copy do not affect the original Better when you need true independence Common deep copy approaches: structuredClone() custom recursive cloning JSON.parse(JSON.stringify(obj)) for simple JSON-safe data only 💻 Example const original = { name: "Alice", address: { city: "Miami" }, scores: [10, 20], }; const shallow = { ...original }; shallow.name = "Bob"; // affects only the copy shallow.address.city = "Tampa"; // affects both shallow.scores.push(30); // affects both console.log(original.address.city); // "Tampa" console.log(original.scores); // [10, 20, 30] Here, name is fine because it’s a primitive. But address and scores are nested references, so both objects still share them. 💻 Deep copy example const original = { date: new Date(), list: [1, 2, 3] }; const deep = structuredClone(original); deep.list.push(4); console.log(original.list); // [1, 2, 3] // Changing the original doesn't affect the copy original.date.setFullYear(2030); console.log(deep.date.getFullYear()); // original change has no effect ⚠️ Important gotchas { ...obj } does not make a deep copy Object.assign() is also shallow JSON.parse(JSON.stringify(obj)) loses things like: functions undefined Date objects as real Dates Map Set cyclic references So for modern JavaScript, structuredClone() is usually the safer built-in option when supported. 🎯 Real-world way to think about it A shallow copy is like copying a folder but keeping the same files inside. A deep copy is like duplicating the folder and duplicating every file inside it too. That’s why nested changes behave differently. 💡 When to use which Use shallow copy when: your data is flat nested data is intentionally shared you only need a quick top-level clone Use deep copy when: nested data must be fully independent you’re working with mutable complex state shared references could cause bugs That difference looks small in code, but it causes a lot of real bugs in apps. #javascript #webdevelopment #frontend #reactjs #softwareengineering #programming #coding #javascriptdeveloper #frontenddeveloper #interviewprep
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