Day 12/50 – JavaScript Interview Question? Question: What is the difference between deep copy and shallow copy? Simple Answer: A shallow copy duplicates only the top-level properties, keeping references to nested objects. A deep copy recursively duplicates all levels, creating completely independent copies. 🧠 Why it matters in real projects: Understanding this prevents bugs when modifying copied objects. In React/Redux, shallow copies are often sufficient for state updates, but nested state requires deep copying. Financial data, user profiles, and configuration objects often need deep copies. 💡 One common mistake: Using spread operator {...obj} or Object.assign() and thinking you have a deep copy. These only perform shallow copies! 📌 Bonus: const original = { name: 'John', address: { city: 'NYC' } }; // Shallow copy - nested objects still shared const shallow = { ...original }; shallow.address.city = 'LA'; console.log(original.address.city); // "LA" - Oops! // Deep copy options: // 1. Modern way (careful with functions/dates) const deep1 = structuredClone(original); // 2. JSON method (loses functions, dates become strings) const deep2 = JSON.parse(JSON.stringify(original)); // 3. Use lodash for complex objects const deep3 = _.cloneDeep(original); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
JavaScript Interview Question: Deep vs Shallow Copy
More Relevant Posts
-
Day 16/50 – JavaScript Interview Question? Question: What's the difference between == comparison and Object.is()? Simple Answer: Both compare values, but Object.is() is more precise. Unlike == (which coerces types) and === (which has special cases for NaN and -0), Object.is() treats NaN as equal to NaN and distinguishes between +0 and -0. 🧠 Why it matters in real projects: While you'll mostly use ===, Object.is() is important for precise comparisons in algorithms, polyfills, and when implementing state management libraries. React uses Object.is() internally for comparing dependencies in hooks. 💡 One common mistake: Not knowing that NaN === NaN is false in JavaScript, which can cause bugs when checking for NaN values in data processing. 📌 Bonus: // Special cases where === fails NaN === NaN // false Object.is(NaN, NaN) // true ✓ +0 === -0 // true Object.is(+0, -0) // false ✓ // For most cases, === works fine Object.is(5, 5) // true 5 === 5 // true Object.is('foo', 'foo') // true 'foo' === 'foo' // true // Checking for NaN the right way Number.isNaN(value) // ✓ Best practice Object.is(value, NaN) // ✓ Also works value !== value // ✓ Clever trick (only NaN !== itself) #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 23/50 – JavaScript Interview Question? Question: What is memoization and how do you implement it? Simple Answer: Memoization is an optimization technique that caches function results based on input arguments. When the function is called again with the same arguments, it returns the cached result instead of recalculating. 🧠 Why it matters in real projects: Memoization dramatically improves performance for expensive computations like recursive Fibonacci, API response parsing, or complex filtering/sorting. React's useMemo and React.memo are built on this principle to prevent unnecessary re-renders. 💡 One common mistake: Over-memoizing everything, which adds memory overhead. Only memoize truly expensive operations. Also, not considering cache size limits, which can cause memory leaks in long-running applications. 📌 Bonus: // Basic memoization implementation function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log('Returning cached result'); return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; } // Usage: Expensive calculation const fibonacci = memoize((n) => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }); fibonacci(40); // Calculated once fibonacci(40); // Instant! (from cache) // React example const expensiveComponent = React.memo(({ data }) => { // Only re-renders if data changes }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 12 Topic: Error Handling in JavaScript (try, catch, finally) Continuing my JavaScript interview revision series, today’s focus was on a very important but often overlooked topic: 👉 Error Handling using try–catch–finally Good developers don’t just write code that works — they write code that handles failures gracefully. 🎪 Real-World Example: Circus Safety Net Imagine a trapeze performance in a circus. 1️⃣ Acrobat attempts a risky trick (TRY). 2️⃣ If something goes wrong, the safety net catches them (CATCH). 3️⃣ After performance, crew resets equipment no matter what (FINALLY). Whether success or failure, cleanup always happens. JavaScript error handling works the same way. 💻 Practical JavaScript Example async function fetchUser() { try { console.log("Fetching user data..."); const response = await fetch("https://lnkd.in/dAktZdHe"); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); console.log("User:", data); } catch (error) { console.error("Something went wrong:", error.message); } finally { console.log("Cleanup: Stop loader / close connection"); } } fetchUser(); Execution Flow ✅ If request succeeds → catch block is skipped ❌ If request fails → catch handles error 🔁 finally runs in both cases ✅ Why Interviewers Ask This Because it tests: • Defensive coding skills • Async error handling understanding • Custom error throwing • Production-ready code thinking 📌 Goal: Share daily JavaScript concepts while preparing for interviews and help others revise fundamentals. Next topics: Event delegation, closures deep dive, execution context, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPreparation #ErrorHandling #AsyncJavaScript #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 19/50 – JavaScript Interview Question? Question: What is the difference between synchronous and asynchronous code? Simple Answer: Synchronous code executes line by line, blocking subsequent code until the current operation completes. Asynchronous code allows other operations to run while waiting for long-running tasks (like API calls) to complete. 🧠 Why it matters in real projects: Asynchronous code prevents UI freezing during network requests, file operations, or heavy computations. Modern web apps rely heavily on async patterns (Promises, async/await) to maintain responsive user interfaces while handling background tasks. 💡 One common mistake: Forgetting to use await with async functions, causing code to continue executing before the promise resolves, leading to undefined values or race conditions. 📌 Bonus: // Synchronous - blocks execution console.log('1'); const result = expensiveOperation(); // Everything waits console.log('2'); console.log(result); // Asynchronous - non-blocking console.log('1'); fetch('/api/data').then(result => { console.log(result); // Executes later }); console.log('2'); // Doesn't wait for fetch // async/await - cleaner async code async function getData() { console.log('1'); const result = await fetch('/api/data'); // Waits here console.log(result); console.log('2'); } // Common mistake async function wrong() { const data = fetch('/api/data'); // Missing await! console.log(data); // Promise object, not the data } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 14/50 – JavaScript Interview Question? Question: What is the difference between map(), forEach(), filter(), and reduce()? Simple Answer: forEach() executes a function for each element (returns undefined). map() transforms each element and returns a new array. filter() returns a new array with elements that pass a test. reduce() accumulates values into a single result. 🧠 Why it matters in real projects: These are essential for functional programming and data transformation. Using the right method makes code more readable and maintainable. React heavily relies on map() for rendering lists, and reduce() is powerful for complex data aggregations. 💡 One common mistake: Using forEach() when you need a return value, or using map() without using the returned array (side effects only). Also, forgetting that these methods don't mutate the original array. 📌 Bonus: const numbers = [1, 2, 3, 4, 5]; // forEach - just iterate (returns undefined) numbers.forEach(n => console.log(n * 2)); // map - transform each element const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10] // filter - keep elements that pass test const evens = numbers.filter(n => n % 2 === 0); // [2, 4] // reduce - accumulate to single value const sum = numbers.reduce((acc, n) => acc + n, 0); // 15 // Chaining for complex operations const result = numbers .filter(n => n > 2) .map(n => n * 2) .reduce((sum, n) => sum + n, 0); // 24 #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 24/50 – JavaScript Interview Question? Question: What is the difference between Object.freeze(), Object.seal(), and Object.preventExtensions()? Simple Answer: Object.freeze() makes an object completely immutable (can't add, delete, or modify properties). Object.seal() prevents adding/deleting properties but allows modifying existing ones. Object.preventExtensions() only prevents adding new properties. 🧠 Why it matters in real projects: These methods enforce immutability and data integrity, crucial for functional programming, Redux state management, and preventing accidental mutations in configuration objects or constants. 💡 One common mistake: Thinking Object.freeze() creates a deep freeze. It only freezes the top level—nested objects remain mutable. You need recursive freezing for complete immutability. 📌 Bonus: // Object.freeze() - completely immutable const frozen = Object.freeze({ name: 'Alice', age: 30 }); frozen.age = 31; // ✗ Ignored (or throws in strict mode) frozen.city = 'NYC'; // ✗ Can't add delete frozen.name; // ✗ Can't delete // Object.seal() - modify only const sealed = Object.seal({ name: 'Bob', age: 25 }); sealed.age = 26; // ✓ Can modify sealed.city = 'LA'; // ✗ Can't add delete sealed.name; // ✗ Can't delete // Object.preventExtensions() - most permissive const limited = Object.preventExtensions({ name: 'Charlie' }); limited.name = 'Chad'; // ✓ Can modify limited.age = 30; // ✗ Can't add delete limited.name; // ✓ Can delete // Deep freeze for nested objects function deepFreeze(obj) { Object.freeze(obj); Object.values(obj).forEach(val => { if (typeof val === 'object' && val !== null) { deepFreeze(val); } }); } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🔹 JavaScript Closures — Lecture 3 | Advanced Understanding & Interview Guide Closures are one of the most important concepts in JavaScript interviews. If you understand this concept deeply, you already think like a senior developer. How Closures Work Internally When a function is returned: ✔ JavaScript keeps its lexical environment ✔ Variables are preserved in memory ✔ Scope chain remains active This is how functions remember outer variables. Common Interview Question 👉 What will be the output? function test(){ for(var i=1; i<=3; i++){ setTimeout(function(){ console.log(i); },1000); } } test(); Output: 4 4 4 Why? var shares the same scope Closure captures final value Solution Using let (Block Scope) for(let i=1; i<=3; i++){ setTimeout(function(){ console.log(i); },1000); } Output: 1 2 3 Why MERN Developers Must Know Closures Closures are used in: ✔ React Hooks ✔ Async JavaScript ✔ Event loop behavior ✔ Callbacks and promises ✔ Functional programming Quick Summary ✔ Closure = function + remembered environment ✔ Enables data privacy ✔ Maintains state ✔ Critical for interviews 🔎 Keywords: advanced JavaScript closures, JavaScript interview preparation, lexical scope JavaScript, MERN stack interview #JavaScriptLearning #MERNStack #FrontendDeveloper #WebDevTips #Programming
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Prep Series — Day 13 Topic: Destructuring & Spread Operator in JavaScript Continuing my JavaScript interview revision journey, today’s focus was on two powerful and commonly used ES6 features: 👉 Destructuring 👉 Spread Operator Both help write cleaner, shorter, and more readable code. 📦 Real-World Example 1️⃣ Destructuring — Unpacking a Box Imagine receiving a box with many items, but you only take what you need: Laptop, charger, headphones, etc. Instead of using the whole box, you extract specific items. JavaScript destructuring works the same way — we extract values from arrays or objects. 2️⃣ Spread Operator — Combining Items Now imagine combining items from multiple boxes into one large container. Spread operator allows us to combine or expand values easily. 💻 Practical JavaScript Examples Array Destructuring const numbers = [10, 20, 30]; const [first, second] = numbers; console.log(first); // 10 console.log(second); // 20 Object Destructuring const user = { name: "Raja", age: 25 }; const { name, age } = user; console.log(name, age); Spread Operator — Combine Arrays const arr1 = [1, 2]; const arr2 = [3, 4]; const combined = [...arr1, ...arr2]; console.log(combined); // [1,2,3,4] Spread — Copy Object const userCopy = { ...user }; ✅ Why This Matters in Interviews Interviewers expect developers to know: • Modern JavaScript syntax • Clean data extraction • Immutable data patterns • Object/array manipulation Destructuring and spread are used everywhere in React and modern JS. 📌 Goal: Share daily JavaScript interview topics while preparing and learning in public. Next topics: Rest operator, shallow vs deep copy, event delegation, and more. Let’s keep improving daily 🚀 #JavaScript #InterviewPreparation #Destructuring #SpreadOperator #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 26/50 – JavaScript Interview Question? Question: What is currying in JavaScript? Simple Answer: Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of add(a, b), you get add(a)(b). 🧠 Why it matters in real projects: Currying enables partial application, function composition, and more reusable code. It's fundamental to functional programming libraries like Ramda and is used in Redux middleware, event handlers, and configuration functions. 💡 One common mistake: Over-currying simple functions where it adds complexity without benefit. Use currying when you need partial application or composition, not everywhere. 📌 Bonus: // Regular function function add(a, b, c) { return a + b + c; } add(1, 2, 3); // 6 // Curried version function curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; }; } curriedAdd(1)(2)(3); // 6 // Practical use: Partial application const add5 = curriedAdd(5); const add5and10 = add5(10); console.log(add5and10(3)); // 18 // Generic curry function function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; } // Usage const multiply = (a, b, c) => a * b * c; const curriedMultiply = curry(multiply); curriedMultiply(2)(3)(4); // 24 curriedMultiply(2, 3)(4); // 24 - flexible! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #FunctionalProgramming #Currying #WebDev #InterviewPrep
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 4 Topic: Higher Order Functions in JavaScript Continuing my JavaScript interview brush-up series, today’s topic is another core JavaScript concept used everywhere in modern development: 👉 Higher Order Functions (HOF) You use them daily in JavaScript, often without realizing it. ☕ Real-World Example: Coffee Shop Customization Imagine ordering coffee. The barista takes: A base drink, and Your custom instructions Then prepares a personalized drink. Mapping to JavaScript Barista → Higher Order Function Custom instructions → Callback Function Final drink → Returned Function / Result So the barista doesn’t just make coffee — they use instructions to customize it. Similarly, Higher Order Functions: ✔ Take functions as input ✔ Or return functions as output 💻 JavaScript Example Example 1 — Using map() const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] Here: map() is a Higher Order Function num => num * 2 is the callback Example 2 — Function Returning Function function createMultiplier(factor) { return function(number) { return number * factor; }; } const double = createMultiplier(2); console.log(double(5)); // 10 The function remembers the factor and creates custom multipliers. ✅ Why This Matters in Interviews Higher Order Functions are everywhere: • map, filter, reduce • Event handling • Functional programming • React patterns • Data transformation logic Understanding them improves code readability and reuse. 📌 Goal: Share daily JavaScript concepts while preparing for interviews and help others revise fundamentals too. Next topics coming: promises, async/await, execution context, hoisting, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPreparation #HigherOrderFunctions #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney #FunctionalProgramming
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