Here’s something commonly asked in JavaScript interviews 👇 Shallow vs Deep Copy Shallow Copy Copies only top-level properties. Nested objects are copied by reference, so changes affect the original. 👉 Ways: Object.assign(), spread (...), Array.from() Deep Copy Creates a fully independent copy, including nested objects. A common approach: JSON.parse(JSON.stringify(obj)) ⚠️ Catch with JSON.stringify() It fails for: • functions (removed) • undefined (removed or become null if arr) • Date (becomes string) • NaN / Infinity (become null) • Map, Set, RegExp (structure lost) • circular references (error) ✅ Better approach const newObj = structuredClone(obj) ✔ Handles most cases (Map, Set, Date, circular refs) ❌ Still can’t clone functions 🔥 Advanced: Custom Deep Clone If you also want to handle functions, you need a custom solution: function deepClone(obj) { if (obj === null || typeof obj !== "object") return obj; if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj === "function") return obj.bind({}); if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } const cloned = {}; for (let key in obj) { cloned[key] = deepClone(obj[key]); } return cloned; } ⚠️ Note: • Functions are copied by reference (true cloning isn’t really possible) 💡 Takeaway • Use shallow copy for simple cases • Use structuredClone() for most real scenarios • Use custom clone only when you need full control Don't forget to follow Mohit Sharma 🚀 for more. #JavaScript #Frontend #WebDevelopment #InterviewPrep #ReactJS
Shallow vs Deep Copy in JavaScript
More Relevant Posts
-
Most developers use JavaScript string methods daily. But very few understand how they actually work under the hood. So I decided to go deeper. In this blog, I break down: • What string methods really are • Why polyfills exist and when they matter • How to implement methods like includes, indexOf, and trim from scratch • Common string problems asked in interviews • The core logic behind string manipulation once you understand the logic, you don’t rely on memorization anymore. https://lnkd.in/gpAPF2_7 #javascript #webdevelopment #frontend #coding #programming #learninpublic #developers #softwareengineering #interviewprep
To view or add a comment, sign in
-
💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
🔥 From JavaScript Interview Questions Challenge: Refactor a function to use lazy evaluation, processing only what’s necessary. Problem Statement The following function calculates the squares of all numbers in a large array and sums them. However, it computes all squares upfront, wasting resources. function sumOfSquares(arr) { const squares = arr.map((num) => num ** 2); return squares.reduce((sum, square) => sum + square, 0); } console.log(sumOfSquares([1, 2, 3, 4, 5])); Solution Use a generator function to calculate squares lazily, avoiding upfront computation. Optimized Code function* lazySquares(arr) { for (const num of arr) { yield num ** 2; // Compute squares lazily } } function sumOfSquares(arr) { let sum = 0; for (const square of lazySquares(arr)) { sum += square; } return sum; } console.log(sumOfSquares([1, 2, 3, 4, 5])); // 55 Explanation 1. Lazy Evaluation: Squares are computed only when required, saving memory for large arrays. 2. Efficiency: Eliminates intermediate storage, reducing space complexity. #javascript #lazyevaluation #generators #interviewprep
To view or add a comment, sign in
-
-
🔥 JavaScript Interview Question That Trips Many Developers Here’s a simple-looking question that reveals how well you understand this in JavaScript 👇 const obj = { name: 'Alice', greet() { console.log(this.name); }, greetArrow: () => { console.log(this.name); }, }; obj.greet(); obj.greetArrow(); const fn = obj.greet; fn(); ❓ What will be the output? ✅ Answer: Alice undefined undefined 💡 Explanation (Must-Know for Interviews): 1️⃣ obj.greet() Regular function this → refers to obj 👉 Output: Alice 2️⃣ obj.greetArrow() Arrow function Doesn’t have its own this Takes this from outer (global) scope 👉 Output: undefined 3️⃣ fn() Function is detached from object this is lost (defaults to global/undefined) 👉 Output: undefined 🧠 Key Takeaways: ✔ this depends on how a function is called ✔ Arrow functions don’t bind this ✔ Extracting methods can break this 💥 Pro Tip: If you want to preserve this: const fn = obj.greet.bind(obj); fn(); // Alice #JavaScript #Frontend #WebDevelopment #InterviewPrep #CodingInterview #JSConcepts
To view or add a comment, sign in
-
Recently in an interview, I was asked about the JavaScript Event Loop… I thought I knew it — but explaining it clearly was harder than expected. So I created this diagram to understand it properly 👇 • Understanding JavaScript Event Loop (Simple Explanation) ° JavaScript Engine JavaScript runs on a single thread. It uses: • Memory Heap → to store data • Call Stack → to execute code 📞 Call Stack All synchronous code runs here. Functions are pushed and popped one by one. 🌐 Web APIs (Browser / Node.js) Async operations are handled outside the JS engine: • setTimeout / setInterval • fetch API • DOM events These APIs run in the background. 📥 Queues Once async work is done, callbacks go into queues: 👉 Microtask Queue (High Priority) • Promise.then() • async/await 👉 Task Queue (Low Priority) • setTimeout • setInterval • DOM events 🔁 Event Loop (Most Important Part) The event loop keeps checking: Is Call Stack empty? Execute ALL Microtasks Then execute ONE Task from Task Queue That’s why Promises run before setTimeout! One Line Summary: JavaScript uses Call Stack + Web APIs + Queues + Event Loop to handle async code without blocking execution. This is one of the most common interview questions — but also one of the most misunderstood. If you can explain this clearly, you’re already ahead of many developers. #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #NodeJS #Frontend #Programming #Interview
To view or add a comment, sign in
-
-
⚡15 JavaScript Senior level questions about objects: 1) How do property descriptors work, and how do get/set interact with writable/configurable/enumerable? 2) Walk through the [[Get]] and [[Set]] algorithm (prototype chain, shadowing, strict mode) 3) What’s the difference between in, hasOwnProperty, and Object.hasOwn? When is Object.hasOwn preferable? 4) Explain Object.create(null) and when you’d use it over {}. 5) this binding in object methods, method extraction, and arrow pitfalls 6) Enumerability, reflection, and key order: for…in vs Object.keys vs Object.getOwnPropertyNames vs Reflect.ownKeys 7) Deep copy strategies: structuredClone, JSON, spread, and Object.assign 8) Freezing, sealing, and extensibility: semantics and pitfalls 9) Proxies, invariants, and why Reflect is your friend 10) Symbols and well-known symbols: make plain objects iterable & controllable 11) Class fields and private fields: what are they actually? 12) super, [[HomeObject]], and why copying methods can break super 13) JSON serialization edge cases: toJSON, replacers, and lost values 14) Property definition vs assignment: descriptors, accessors, and side effects 15) Objects vs Map/WeakMap: key types, iteration, GC, and performance #JavaScript #TechInterview
To view or add a comment, sign in
-
🤫While revising JavaScript for interviews, I was going through one of the most confusing (and interesting) topics: Type Coercion. Especially the rules behind Abstract Equality ("==") from the ECMAScript specification. Honestly, questions like these can easily make you doubt your JavaScript fundamentals if you don’t understand how coercion actually works. If you’re not able to solve them or explain them clearly, it’s a good sign to revise the core concepts again.😌 😜Here are some classic interview questions: console.log([] == ![]); // true console.log(![] == false); // true console.log([] == []); // false console.log([] == 0); // true console.log([0] == 0); // true console.log([1] == true); // true console.log([] == ''); // true These are not just “tricky JS puzzles” — they test your understanding of: • Type conversion rules😏 • Truthy vs Falsy values • Primitive conversion ("ToPrimitive") • Number conversion ("ToNumber") • Boolean conversion ("ToBoolean") • Object reference comparison • Abstract Equality Algorithm ("==") Most developers memorize the answers. Better developers understand why.🤔 That’s where real interview confidence comes from.😎 Currently revising this deeply, and honestly, every time I study it, I find something new. JavaScript looks simple… until "==" enters the chat 😬 #JavaScript #FrontendDevelopment #InterviewPreparation #FrontendInterview #CodingInterview
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
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
To view or add a comment, sign in
Explore related topics
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