<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abubakkar Siddhiq on Medium]]></title>
        <description><![CDATA[Stories by Abubakkar Siddhiq on Medium]]></description>
        <link>https://medium.com/@Abubakkar-Siddhiq?source=rss-ecadaa3a6ea9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nBqb50uZrgyYEnwvv2N9fg.jpeg</url>
            <title>Stories by Abubakkar Siddhiq on Medium</title>
            <link>https://medium.com/@Abubakkar-Siddhiq?source=rss-ecadaa3a6ea9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:14:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Abubakkar-Siddhiq/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built a Distributed Payment System from Scratch (And What It Taught Me)]]></title>
            <link>https://medium.com/@Abubakkar-Siddhiq/how-i-built-a-distributed-payment-system-from-scratch-and-what-it-taught-me-9086c00ebca4?source=rss-ecadaa3a6ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9086c00ebca4</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Abubakkar Siddhiq]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 07:03:06 GMT</pubDate>
            <atom:updated>2026-04-29T07:03:06.662Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A honest account of building something I had no business building, and finishing it anyway.</em></p><h3>Why I Built This</h3><p>I’ve always been fascinated by how money moves on the internet.</p><p>When you tap “Pay” on GPay, something happens in milliseconds. Money leaves your account, reaches someone else’s, a notification fires, a fraud check runs. All simultaneously, all reliably, even when things go wrong. I never really understood how.</p><p>So I decided to stop wondering and start building.</p><p>This isn’t a tutorial. It’s the <strong>Story of building a Distributed Payment Processing System</strong>. The kind of infrastructure that sits underneath apps like Razorpay or PayPal and the hard lessons I learned along the way.</p><h3>What I Set Out to Build</h3><p>Not a UPI clone. Not a wallet app. The engine underneath.</p><p>A system that could:</p><ul><li>Move money reliably between accounts</li><li>Never process the same payment twice</li><li>Detect and respond to fraud in real time</li><li>Survive crashes without losing a single transaction</li></ul><p>Six microservices. Five Kafka topics. Three databases. One month.</p><h3>The Architecture (And Why I Made These Choices)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3AtwY1MEpeMwQg53-sgZQ.png" /></figure><h3>Why microservices?</h3><p>Honestly? I could have built this as a monolith. For a personal project, a monolith would have been faster.</p><p>But I wanted to understand something specific, what happens when services need to communicate without calling each other directly? What happens when one service goes down? How do you guarantee a payment notification fires even if the notification service was offline for an hour?</p><p>These are questions you can only answer by building distributed systems.</p><h3>The Services (What Each One Actually Does)</h3><p>Most microservices tutorials show you five boxes in a diagram and call it architecture.</p><p>Here’s what each service actually does and why it exists as its own thing.</p><p><strong>API Gateway </strong>— the front door. Every request hits here first. JWT<br>validated, rate limited, role checked, then routed. Internal services<br>never see an unauthenticated request. They trust the X-User-Id header<br>Gateway injects because only Gateway can set it.</p><p><strong>Auth Service</strong> — issues identity. Register, login, JWT. That’s it.<br>When a user registers, it publishes a `user-registered` event to Kafka.<br>Payment Service picks that up and creates an account automatically.<br>No HTTP call between services. No coupling. Auth Service doesn’t know<br>Payment Service exists.</p><p><strong>Payment Service</strong> — the brain. Every interesting problem lives here.<br>Double-entry ledger, idempotency, pessimistic locking, outbox pattern,<br>saga compensation. If this service gets something wrong, money is lost<br>or duplicated. There’s no margin for error here.</p><p><strong>Fraud Service</strong> — the watchdog. Consumes every payment event and runs<br>it through a rules engine. High value transaction? Flag it. Round number?<br>Flag it. Self-transfer? Flag it. Flagged transactions go into a review<br>queue. Admins approve or reject. Rejection triggers a compensation event<br>back to Payment Service reverse the transaction, freeze the account.</p><p><strong>Notification Service</strong> — the simplest service and the most<br>underappreciated. One job: consume payment events and notify the user.<br>It’s separate from Payment Service for one reason. If your email<br>provider is having a bad day, payments should still work. Decoupling<br>failure domains is the point.</p><h3>Why Kafka over RabbitMQ?</h3><p>Early on I asked myself this question. Both are message brokers. Both could work.</p><p>The difference came down to one scenario: what if my Fraud Service goes down for 30 minutes? With RabbitMQ fanout, those payment events are gone. With Kafka’s message retention, Fraud Service catches up on restart. Every event processed. Nothing lost.</p><p>For a payment system, losing events isn’t an option. Kafka won.</p><h3>The Hard Problems (This Is The Good Part)</h3><h3>Problem 1: What if the same payment request is sent twice?</h3><p>Network timeouts are real. A client sends a payment request, the network drops, the client retries. Without protection you charge someone twice.</p><p>The solution is <strong>Idempotency</strong>. Every payment request carries a client-generated key. Before processing, I check Redis:</p><ul><li>Key exists with SUCCESS? Return same response. Don’t process again.</li><li>Key exists with PROCESSING? Another request is in flight. Return 409.</li><li>Key doesn’t exist? Process it. Store key with PENDING. Update to SUCCESS or FAILED.</li></ul><p>Simple concept. Surprisingly tricky to implement correctly. The atomic setIfAbsent operation in Redis was the key. without it, two concurrent requests could both pass the check simultaneously.</p><h3>Problem 2: What if two payments hit the same account at the same time?</h3><p>Imagine User A has ₹1000. Two payment requests arrive simultaneously, Both want to deduct ₹800. Both read the balance as ₹1000. Both see enough funds. Both process. User A’s balance goes to -₹600.</p><p><strong>Pessimistic locking</strong> fixed this. When I fetch an account for payment processing, I lock that DB row. The second request waits. When the first commits, the second reads the updated balance ₹200 and correctly fails.</p><p>One annotation. @Lock(LockModeType.PESSIMISTIC_WRITE). Weeks of potential bugs prevented.</p><h3>Problem 3: What if my service crashes after saving the transaction but before publishing to Kafka?</h3><p>This one kept me up at night.</p><p>Payment saved to DB. Then crash. Kafka event never fires. Fraud Service and Notification Service never know the payment happened. Silent data loss.</p><p>The <strong>Outbox Pattern </strong>solved this. Instead of publishing to Kafka directly, I write the event to an outbox table in the same database transaction. A separate scheduler reads unpublished events and publishes them. Since the DB write and the outbox write happen in the same transaction either both succeed or neither does.</p><p>The scheduler handles Kafka. If Kafka is down, the scheduler retries. No events lost. Ever.</p><h3>Problem 4: How do you reverse a payment after it’s already processed?</h3><p>Fraud detection is async. By the time I detect a suspicious transaction, the money has already moved.</p><p>You can’t just delete the transaction. Financial systems never delete. Instead, I implemented the <strong>Saga pattern</strong>. When Fraud Service confirms fraud, it publishes a compensation event. Payment Service consumes it and creates a compensating transaction. credit the sender back, debit the receiver, freeze the account.</p><p>Two transactions. Books balance. Full audit trail. No data deleted.</p><h3>What I Got Wrong (And Fixed)</h3><p><strong>Using </strong><strong>float for money.</strong> Floating point arithmetic gives you things like 0.1 + 0.2 = 0.30000000000000004. In a payment system, that&#39;s unacceptable. Switched to BigDecimal everywhere. Lesson: never use floating point for money.</p><p><strong>Publishing directly to Kafka from within </strong><strong>@Transactional.</strong> Kafka publish happens outside the DB transaction. If the transaction rolls back, the Kafka event is already out. The Outbox Pattern fixed this, but I had to understand the problem first by making the mistake.</p><p><strong>Checking idempotency after building the transaction object.</strong> Early version built the transaction, then checked idempotency, then processed. Wrong order. Idempotency check goes first before any work is done.</p><p><strong>Returning </strong><strong>null instead of </strong><strong>Optional.</strong> Classic Java mistake. Switched every repository method to return Optional and forced myself to handle the empty case explicitly.</p><h3>The Security Thinking</h3><p>Building a payment system forces you to think about security differently.</p><p>Every design decision becomes a security question:</p><ul><li>Who owns this account? (Ownership validation on every write)</li><li>Can someone fake the user identity header? (Strip untrusted headers at Gateway, inject verified ones)</li><li>What if someone brute forces login? (Rate limiting 5 requests/minute per IP)</li><li>What if someone decodes the JWT and changes the user ID? (JWT signature validation can’t forge without the secret)</li><li>Can someone see other users’ balances? (Account number abstraction UUIDs stay internal)</li></ul><p>Security isn’t a feature you add at the end. It’s a question you ask at every step.</p><h3>What I Learned</h3><p><strong>Distributed systems fail in interesting ways.</strong> Not “server is down” failures. Subtle failures. Message delivered twice, event lost between two healthy services, race condition that only appears under load. Building for failure is the job.</p><p><strong>Complexity compounds.</strong> Every pattern I added Outbox, Saga, Idempotency solved a real problem but added surface area. There’s a reason experienced engineers say “start simple.” I added complexity deliberately, one problem at a time.</p><p><strong>The questions matter more than the answers.</strong> The best moments weren’t when I solved problems. They were when I asked the right question.</p><p><strong>“What happens if this service crashes here?”</strong> led to the <strong>Outbox Pattern</strong>.</p><p><strong>“What if two requests arrive simultaneously?”</strong> led to <strong>pessimistic locking</strong>.</p><p>Learning to ask better questions is the real skill.</p><p><strong>Understanding beats memorizing.</strong> I could have copied a microservices tutorial. Instead I built it from the problem up. Understood why Kafka, why Redis, why separate databases. That understanding is what I can take into any system, any language, any problem.</p><h3>Thanks for Reading 💖</h3><p>If this post resonated or you have questions about any of the patterns kindly do reach out. I’m always happy to talk distributed systems.</p><p><em>GitHub: </em><a href="https://github.com/Abubakkar-Siddhiq/payment-system/">https://github.com/Abubakkar-Siddhiq/payment-system/</a><br><em>Tech: Spring Boot 4.x · Kafka · Redis · PostgreSQL · Docker · Grafana LGTM</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9086c00ebca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Async JavaScript: Callbacks and the Rise of Callback Hell]]></title>
            <link>https://medium.com/@Abubakkar-Siddhiq/understanding-async-javascript-callbacks-and-the-rise-of-callback-hell-2b2639bf644a?source=rss-ecadaa3a6ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2639bf644a</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Abubakkar Siddhiq]]></dc:creator>
            <pubDate>Sat, 10 May 2025 05:39:41 GMT</pubDate>
            <atom:updated>2025-05-10T05:39:41.576Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Callback function is a Function that is passed as an argument to another function, which is then invoked inside it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*hs6pnLGEIQsJqaaoYt5JhQ.png" /></figure><p>Before we dive into callbacks, let&#39;s see how synchronous and asynchronous code work in JavaScript.</p><h3>Synchronous and Asynchronous</h3><h4>Synchronous</h4><p>In Sync, each task is executed one after another. In a sequence. So, if a task is consuming too much time, it’ll freeze the call stack.</p><p>Imagine you’re driving on a single-lane road, and the car in front of you is moving extremely slowly. Even though the road ahead is completely clear. Until that driver speeds up or moves aside, you’re stuck behind them, and so are all the cars behind you. As a result, everyone is delayed in reaching their destination, all because one person is driving so slowly that even a guy on a bicycle could overtake him.</p><p>Eg:</p><pre>function slowGuy() {<br>  console.log(&quot;Guy driving his car on First gear in an empty road. 🚗&quot;)<br>  for (let i = 0; i &lt; 1_000_000_000; i++) {<br>    // doing some meaningless work to eat up time<br>    Math.sqrt(i);<br>  }<br>}<br><br>console.log(&quot;Your friend&#39;s car 🚗&quot;);<br><br>slowGuy(); // About 15-17 mins of delay 💢<br><br>console.log(&quot;Your Car 🚗&quot;);<br><br>// See due to this slowGuy it&#39;s gonna take you a long time to catch-up with<br>// your friend. :(</pre><h4>Asynchronous</h4><p>On the other hand, Async code won’t run in a sequence. It will wait for no one. It’ll start executing a new task while executing a time-consuming task alongside. Due to this non-blocking nature, Async code allows JavaScript to handle multiple tasks concurrently without freezing the application, improving performance and responsiveness, especially for tasks like API calls, file reads, or timers.</p><p>Imagine a chef in a busy restaurant during peak hours. He receives multiple food orders at once. Now, he gets two orders: one for pasta and another for a French omelet, both of which need to be ready at the same time. So, he starts boiling the pasta on one stove, then grabs a pan, cracks an egg, and begins cooking the omelet. Notice how he doesn’t wait for the pasta to finish boiling. He lets it cook in the background while he works on the next dish. That’s an async chef.</p><p>Eg:</p><pre>// Chef&#39;s Den (Kitchen!)<br><br>console.log(&quot;One Pasta for Table 5&quot;);<br>console.log(&quot;One French Omelet for Table 7&quot;);<br><br>// Start boiling the pasta (takes time)<br>setTimeout(() =&gt; {<br>  console.log(&quot;Pasta for Table 5 is ready! 🍝&quot;);<br>}, 3000); // simulating 3 seconds boiling time<br><br>// Cook the omelet immediately<br>console.log(&quot;Cooking French Omelet for Table 7...&quot;);<br>console.log(&quot;French Omelet for Table 7 is ready! 🍳&quot;);<br><br>console.log(&quot;Chef continues with other orders...&quot;);<br><br>// Output:<br>// - One Pasta for Table 5<br>// - One French Omelet for Table 7<br>// - Cooking French Omelet for Table 7...<br>// - French Omelet for Table 7 is ready! 🍳<br>// - Chef continues with other orders...<br>// - Pasta for Table 5 is ready! 🍝</pre><h3>Callback!</h3><p>A Callback function is a function that you pass into another function as a parameter. And then you can decide when it should be invoked.</p><pre>function getUserName(callback) {<br>  setTimeout(() =&gt; {<br>    const name = &quot;Alice&quot;;<br>    callback(name); // Call the callback with the name<br>  }, 2000); // Simulate a 2-second delay (like fetching from a database)<br>}<br><br>function greet(name) {<br>  console.log(`Hello, ${name}!`);<br>}<br><br>// Call the function and pass `greet` as a callback<br>getUserName(greet);<br><br>// Output: Hello, Alice --&gt; is printed after 2 seconds.</pre><h4>Why use a Callback?</h4><p>Callbacks can be used when dealing with asynchronous operations such as reading a file, making an API request, or waiting for user input, as these operations take time. They can also prevent blocking the call stack.</p><p>Array methods like .map(), .filter(), .forEach() All take callbacks. You can pass a callback function and define what should happen next.</p><h3>The Catch: Callback Hell🔥</h3><p>Callback Hell, aka. The Pyramid of Doom. Happens when multiple callbacks are nested inside your code, making it look like a Pyramid sideways. The Problem? Hard to read, Hard to maintain code.</p><pre>asyncFunction1((result1) =&gt; {<br>  asyncFunction2(result1, (result2) =&gt; {<br>    asyncFunction3(result2, (result3) =&gt; {<br>      asyncFunction4(result3, (result4) =&gt; {<br>        console.log(result4);<br>      });<br>    });<br>  });<br>});</pre><p>Let’s understand this better with a real-world example.</p><pre>const getUser = (userId, callback) =&gt; {<br>  setTimeout(() =&gt; callback(null, { id: userId, name: &quot;Bob&quot; }), 500);<br>};<br><br>const getActivity = (userId, callback) =&gt; {<br>  setTimeout(() =&gt; callback(null, [&quot;Logged in&quot;, &quot;Posted update&quot;]), 500);<br>};<br><br>// Callback Hell<br>getUser(1, (err, user) =&gt; {<br>  if (err) return console.error(&quot;Error:&quot;, err);<br>  console.log(&quot;User:&quot;, user.name);<br>  getActivity(user.id, (err, activity) =&gt; {<br>    if (err) return console.error(&quot;Error:&quot;, err);<br>    console.log(&quot;Activity:&quot;, activity);<br>  });<br>});</pre><p>See, here we’re trying to fetch user information and their recent activity from an API. But the code looks messy, with Nested Callbacks and is hard to read.</p><h3>The Solution?</h3><h4>Promises</h4><p>We can use Promises to handle Async operations and avoid deep nesting.</p><pre>const getUser = (userId) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; resolve({ id: userId, name: &quot;Bob&quot; }), 500);<br>  });<br>};<br><br>const getActivity = (userId) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; resolve([&quot;Logged in&quot;, &quot;Posted update&quot;]), 500);<br>  });<br>};<br><br>getUser(1)<br>  .then((user) =&gt; {<br>    console.log(&quot;User:&quot;, user.name);<br>    return getActivity(user.id);<br>  })<br>  .then((activity) =&gt; console.log(&quot;Activity:&quot;, activity))<br>  .catch((err) =&gt; console.error(&quot;Error:&quot;, err));</pre><p>See the code is much cleaner and more readable now. .then() chaining avoids nesting and .catch() takes care of the errors.</p><h4>Async / Await</h4><p>Async/Await makes code look like synchronous code, making it more readable. A singletry/catch is enough to handle errors.</p><pre>const getUser = (userId) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; resolve({ id: userId, name: &quot;Bob&quot; }), 500);<br>  });<br>};<br><br>const getActivity = (userId) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; resolve([&quot;Logged in&quot;, &quot;Posted update&quot;]), 500);<br>  });<br>};<br><br>async function fetchData() {<br>  try {<br>    const user = await getUser(1);<br>    console.log(&quot;User:&quot;, user.name);<br>    const activity = await getActivity(user.id);<br>    console.log(&quot;Activity:&quot;, activity);<br>  } catch (err) {<br>    console.error(&quot;Error:&quot;, err);<br>  }<br>}<br><br>fetchData();</pre><p>See, the code became just as simple as synchronous code. Easy to read and maintain, yay!</p><h4>Conclusion</h4><p>If there’s only a single async operation, it’s ok to use callbacks. But if it gets more complex, instead of nesting, it&#39;s advisable to move to Promises or Async/Await for better code readability and maintainability.</p><blockquote>Thank You for Reading 💖</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2639bf644a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shallow Copy vs Deep Copy in JavaScript: Which should you use?]]></title>
            <link>https://medium.com/@Abubakkar-Siddhiq/shallow-copy-vs-deep-copy-in-javascript-which-should-you-use-97413110272e?source=rss-ecadaa3a6ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/97413110272e</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Abubakkar Siddhiq]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 06:48:23 GMT</pubDate>
            <atom:updated>2025-04-15T05:43:33.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*IXXVu8hUWo32I0wU.jpg" /></figure><p><em>Hey, have you ever ran into a problem where you clone an object, and start editing the cloned object, but somehow the original object gets overwritten? <br>How frustrating is that?! In this article, I’ll explain how to clone objects correctly using the right methods.</em></p><h3>Methods of Cloning</h3><p>There are two ways to clone an object in JavaScript.</p><ul><li><strong>Shallow Copy: </strong>Shallow Copy copies only the <strong>First level of the Object.</strong> Deeper levels of the object are just referenced to the original object.</li><li><strong>Deep Copy: </strong>Deep Copy copies <strong>All levels of the Object. </strong>Gives us a completely independent copy of the Original.</li></ul><p><em>Let’s see how we can clone an Object using these methods.</em></p><h3>Shallow Copy</h3><p>We can shallow copy an object by 2 methods:</p><h4><strong>Using Spread Operator (…)</strong></h4><pre>// Original object<br>const original = { <br>  a: 1,<br>  b: [1, 2, 3]<br>};<br><br>// Shallow copy using spread operator<br>const shallowCopy = { ...original };<br><br>// Modify nested array in shallow copy<br>shallowCopy.b[0] = 99;<br><br>// Check both objects<br>console.log(&quot;Original:&quot;, original);     // Output: { a: 1, b: [99, 2, 3] }<br>console.log(&quot;Shallow Copy:&quot;, shallowCopy); // Output: { a: 1, b: [99, 2, 3] }</pre><h4><strong>Using Object.assign()</strong></h4><pre>// Original object<br>const original = { a: 1, b: [1, 2, 3] };<br><br>// Shallow copy using Object.assign<br>const shallowCopy = Object.assign({}, original);<br><br>// Modify nested array in shallow copy<br>shallowCopy.b[0] = 99;<br><br>// Check both objects<br>console.log(&quot;Original:&quot;, original);     // Output: { a: 1, b: [99, 2, 3] }<br>console.log(&quot;Shallow Copy:&quot;, shallowCopy); // Output: { a: 1, b: [99, 2, 3] }</pre><p>This Method of Copying/Cloning is Faster than Deep Copy. But that comes with a cost.</p><p>See, When we modify the cloned object. The Original was also modified. Bad. When used in work. It’ll cause unnecessary errors.</p><h3>Deep Copy</h3><p>We can Deep Copy an Object using 3 Methods:</p><h4><strong>Using </strong><strong>JSON.stringify() and </strong><strong>JSON.parse()</strong></h4><p>Converts JSON to String then parses it back to JSON. But it ignores properties like functions, undefined, Symbol and date.</p><pre>// Original object<br>const original = { <br>  a: 1,<br>  b: [1, 2, 3]<br>};<br><br>// Deep copy using JSON parse and stringify<br>const deepCopy = JSON.parse(JSON.stringify(original));<br><br>// Modify nested array in a deep copy<br>deepCopy.b[0] = 99;<br><br>// Check both objects<br>console.log(&quot;Original:&quot;, original);     // Output: { a: 1, b: [1, 2, 3] }<br>console.log(&quot;Deep Copy:&quot;, deepCopy); // Output: { a: 1, b: [99, 2, 3] }<br><br>// Original is Intact! 🥳</pre><h4>Shallow Copying at Every Level?</h4><p>Yes, You can try shallow copying the object at every level if the object is small and not complicated.</p><pre>// Original object<br>const original = { <br>  a: 1,<br>  b: [1, 2, 3]<br>};<br><br>// Deep copy using Shallow Copy at every level<br>const deepCopy = {<br>  ...a,<br>  b: [...original.b]<br>}<br><br>// Modify nested array in a deep copy<br>deepCopy.b[0] = 99;<br><br>// Check both objects<br>console.log(&quot;Original:&quot;, original);     // Output: { a: 1, b: [1, 2, 3] }<br>console.log(&quot;Deep Copy:&quot;, deepCopy); // Output: { a: 1, b: [99, 2, 3] }<br><br>// Original is Intact! 🥳</pre><h4>Using structuredClone()</h4><p>structuredClone() is JavaScript’s Built-in Function used to Deep-Clone objects.</p><pre>// Original object<br>const original = { <br>  a: 1,<br>  b: [1, 2, 3]<br>};<br><br>// Deep copy using Shallow Copy at every level<br>const deepCopy = structuredClone(original);<br><br>// Modify nested array in a deep copy<br>deepCopy.b[0] = 99;<br><br>// Check both objects<br>console.log(&quot;Original:&quot;, original);     // Output: { a: 1, b: [1, 2, 3] }<br>console.log(&quot;Deep Copy:&quot;, deepCopy); // Output: { a: 1, b: [99, 2, 3] }<br><br>// Original is Intact! 🥳</pre><h4>Bonus: Third-Party Libraries</h4><p>You can use third-party libraries like <strong>Lodash</strong> to create Deep Copy of Objects.</p><pre>import _ from &#39;lodash&#39;;<br>const deepCopy = _.cloneDeep(originalObject);</pre><h3>Which Should You Choose?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*lc5JO4xQITUzWRHSsYCA6Q.png" /></figure><h4>Shallow Copy</h4><p>When can you use Shallow Copy?</p><ul><li><strong>Flat Objects: </strong>Objects without nested properties</li><li><strong>Performance: </strong>If you want speed and don&#39;t care about deeply nested data.</li><li><strong>Top-Level Props: </strong>If you only care about Top level properties then its fine to use Shallow Copy.</li></ul><h4>Deep Copy</h4><p>When can you use Deep Copy?</p><ul><li><strong>Complex Objects: </strong>Cloning Deeply nested complex objects.</li><li><strong>Independence: </strong>If you don&#39;t want the changes of the cloned object to affect the original object.</li><li><strong>State Management: </strong>In Frameworks like React, Redux where immutability is crucial.</li></ul><p>Understanding the difference between Shallow and Deep copy is crucial for Error-Free JavaScript Code. And, Knowing when to use which is also important. I hope this article gave you enough clarity.</p><blockquote><em>That’s it! If you’ve read till here. Thank You so much! 💖</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97413110272e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Closure in JavaScript: Scopes, Lexical Environment, Use-Cases and More.]]></title>
            <link>https://medium.com/@Abubakkar-Siddhiq/mastering-closure-in-javascript-scopes-lexical-environment-use-cases-and-more-75d8c3177768?source=rss-ecadaa3a6ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/75d8c3177768</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Abubakkar Siddhiq]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 06:23:09 GMT</pubDate>
            <atom:updated>2025-04-04T04:52:40.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*cTkxjYtbJe6SmmLILEnOxg.png" /></figure><p><em>Ever wondered how a function can remember its Parent’s/Outer Function’s variables even after the Parent/Outer Function finishes its Execution? <br>That’s Closure 🪄</em></p><p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time. <br>— <em>MDN</em></p><p>Before we dive into learning Closures.. We first need to learn a few things like: Scopes, Execution Context, and Lexical Environment. Let&#39;s see them one by one.</p><h3>Scopes 🔦</h3><p>Scopes in JavaScript are like a searchlight that the JavaScript engine uses to find variables. When you ask the engine to retrieve a variable’s value, it starts by searching the current (Local) scope. If the variable isn’t found there, it moves up the scope chain, checking each outer scope, including nested functions, until it reaches the Global scope. If the variable is found, its value is returned. If it’s declared but unassigned, the value is undefined. If the variable isn’t found anywhere in the scope chain, the engine throws a ReferenceError</p><p>Scope determines where the variables are created and from where they can be accessed.</p><p><strong>There are 4 types of Scopes in JS:</strong></p><ul><li>Global Scope</li><li>Local Scope</li><li>Module Scope</li><li>Block Scope</li></ul><h4><strong>Global Scope:</strong></h4><p>Variables declared outside of any function/block are <strong>Global Scope </strong>and they can be accessed anywhere in the code.</p><pre>var globalVar = &quot;I&#39;m Global&quot;;<br><br>function printSomething() {<br>  console.log(globalVar);<br>}<br><br>printSomething(); // I&#39;m Global</pre><h4>Local Scope:</h4><p>Variables declared inside a function and they can only be accessed in the function are <strong>Local Scope</strong> variables.</p><pre>function local() {<br>  var localVar = &quot;I&#39;m Local&quot;;<br>  console.log(localVar); // I&#39;m Local<br>}<br><br>console.log(localVar); // ReferenceError: localVar is not defined</pre><h4>Block Scope</h4><p>Variables which are declared inside {}using let or const are accessible only within that block. Like: variables declared inside a for-loop, while-loop, if-else block, etc.,</p><pre>function block() {<br>  if (true) {<br>    var one = &quot;I&#39;m function-scoped with var&quot;;<br>    let two = &quot;I&#39;m block-scoped with let&quot;;<br>  }<br><br>  console.log(one); // &quot;I&#39;m function-scoped with var&quot;<br>  console.log(two); // ReferenceError: two is not defined<br>}<br><br>compareScopes();</pre><h3>Execution Context ⚙️</h3><p>Execution Context is the Internal Runtime Environment created whenever code is executed, containing all the necessary information for tracking variables, scope chains, and the value of this during that specific execution. There are two types of Execution Contexts:</p><ul><li><strong>Global Execution Context (GEC)</strong> → Created when the JavaScript script starts running.</li><li><strong>Function Execution Context (FEC) </strong>→ Created whenever a function is invoked.</li></ul><h3>Understanding Lexical Environment 🌲</h3><p>Whenever an Execution Context is created, a corresponding Lexical Environment is created. This Lexical Environment consists of two key components:</p><ol><li><strong>Environment Record — </strong>Stores all local variables, function declarations, and parameters in the current scope.</li><li><strong>Reference to the Outer Environment — </strong>A link to the Lexical Environment of the Enclosing Scope/Parent Function.</li></ol><p>I know it may be a bit overwhelming to understand this. Let me explain this with an Analogy 😁</p><h4>Lexical Environment Analogy: “<em>Bro, Can u spare me a pen?” 🖊️</em></h4><p>Think you’re sitting in your Classroom. Last bench, Next to a window (Nice place to Sleep during boring lectures, of course). Now suddenly you realize you wanna take notes but you don’t have a Pen! So you do what anyone would do… Bug the guy in front of you for a Pen. If he has one, he’ll give you, else he’ll ask the guy in front of him until it reaches the First bench guy. If you’re lucky you’ll get a Pen. Else Reference Error</p><p>Let’s break this Scene down! See…</p><ul><li><strong>Last Bench Guy (you)</strong> — Inner-most function</li><li><strong>The Guy in front of you </strong>— Your parent function (outer function)</li><li><strong>The Chain of Students</strong> — (Students from Last to First Bench) The Scope Chain!</li><li><strong>The Pen</strong> — Variable you’re trying to access.</li><li><strong>The First Bench Student</strong> — Global Scope.</li></ul><p>Just like <strong>we can only ask the guy in front of us, </strong>A function can only directly access it’s Parent’s variables. However, Due to Lexical Scope, If the variable is not found in the immediate scope, JS just keeps looking up the Scope chain. JavaScript’s Lexical Environment/Scope is the most resilient warrior who never returns until he finds what he wants. So that’s it… I hope you understood this, Let’s move on and Seek Closure!</p><h3>Closures!</h3><p>A Closure is formed when a function retains a reference to variables from its outer (enclosing) scope. This allows the function to remember and use those variables even after the outer function has finished executing.</p><p>Hey, How can a function ‘remember’ variables long after its parent function has finished running? <em>That’s the magic of closures! 🪄</em></p><p>Example:</p><pre>function outerFun() {<br>  let count = 0;<br>  <br>  return function() { // This is the inner-function<br>    count++;<br>    return count;<br>  }<br>}<br><br>const add = outerFun();<br><br>add(); // 1<br>add(); // 2 ... So on. Even after the outerFun() is Executed, The inner-function still can access its variables see..</pre><p>Ok, Lemme wrap this up with an Analogy 😁 and we can move on to <strong>Use-Cases of Closures.</strong></p><h4>Closure Analogy: The Guy Who Can’t Move On 💔</h4><p>See, Closure in JavaScript is just a guy who can’t move on. It’s that simple!<br>Let’s imagine there’s a Guy who fell head over heels for a Girl. He loved her soo deeply and Shit happened and they broke up. Years have passed and he still can’t forget her and move on. Still thinking about her. Ordinary stuff… But this will help us understand Closures 😂. Lemme break it down!</p><ul><li><strong>The Girl — </strong>Outer Function</li><li><strong>Our Guy — </strong>Inner Function</li><li><strong>Memories — </strong>Outer Function variables (This is the thing Bro can’t forget and haunts him daily).</li><li><strong>He can’t move on — </strong>No, He won’t forget the memories… Because JavaScript is designed like that.</li></ul><p>So, even after the Girl breaks up with him (Outer function finishes its execution), Bro can’t move on or forget those memories (Inner Function still retains outer-function variables reference). Bro stays like that for Life. Bro won’t move on… But we’ve to. Let’s see the Use-Cases.</p><h3>Use-Cases of Closures</h3><p>Here are a few real-world use cases of Closures 👇</p><h4>1. Encapsulation</h4><p>Closures let us create private variables that can only be accessed and modified through exposed methods.</p><pre>function simpleMath() {<br>  let num=0;<br><br>  return {<br>    add: function (){ ++num; return num },<br>    subtract: function (){ --num; return num},<br>  }<br>}<br><br>const m = simepleMath();<br>m.add()   // 1<br>m.add()   // 2<br>m.subtract()  // 1</pre><h4>2. Function Factories</h4><p>Closures let us create custom functions dynamically based on the Parameters we pass. It’s called a Factory Function. This function returns a new function which is tailored to specific tasks based on the argument that we passed.</p><pre>function createCustomGreeter(greeting) {<br>  return function(name) {<br>    return `${greeting}, ${name}`;<br>  };<br>}<br><br>const casualGreeter = createCustomGreeter(&quot;Hey&quot;);<br>const formalGreeter = createCustomGreeter(&quot;Good day&quot;);<br>const excitedGreeter = createCustomGreeter(&quot;WELCOME&quot;);<br><br>console.log(casualGreeter(&quot;Taylor&quot;));  // &quot;Hey, Taylor&quot;<br>console.log(formalGreeter(&quot;Dr. Smith&quot;));  // &quot;Good day, Dr. Smith&quot;<br>console.log(excitedGreeter(&quot;TEAM&quot;));  // &quot;WELCOME, TEAM&quot;</pre><h4>3. Iterators</h4><p>Closures as Iterators are like Bookmarks in a book. They remember their current position in the iteration even after they’re executed.</p><pre>function createArrayIterator(array) {<br>  let index = 0;  // Position to be remembered between each calls  <br>  return {<br>    getNext: function() {<br>      if (index &lt; array.length) {<br>        return array[index++];  // Return current item and advance position<br>      } else {<br>        return &quot;End of collection&quot;;<br>      }<br>    }<br>  };<br>}<br><br>const namesIterator = createArrayIterator([&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]);<br><br>console.log(namesIterator.getNext());  // &quot;Alice&quot;<br>console.log(namesIterator.getNext());  // &quot;Bob&quot;<br>console.log(namesIterator.getNext());  // &quot;Charlie&quot;<br>console.log(namesIterator.getNext());  // &quot;End of collection&quot;</pre><h4>4. Event handlers with Preserved state</h4><p>Closures can capture and preserve contextual data at Event Handler’s creation time. And it ensures that the data remains the same whenever the event triggers.</p><pre>function setupButtonHandler(buttonId, message) {<br>  const button = document.getElementById(buttonId);<br>  button.addEventListener(&#39;click&#39;, function() {<br>    alert(message); // message is preserved in closure<br>  });<br>}<br><br>setupButtonHandler(&quot;myBtn&quot;, &quot;Hello, Closure!&quot;); // Whenever the button is Clicked, it alerts &quot;Hello, Closure&quot;</pre><h4>5. Currying</h4><p>Currying is a technique in Functional Programming where a function doesn&#39;t take all the arguments at once. But instead it returns a function to take the next argument and this cycle goes on for the number of arguments it’s about to receive.</p><pre>function add(a) { // a First argument<br>  return function(b) { // b Second argument<br>    return a + b;<br>  };<br>}<br><br>const add5 = add(5); // 5 is passed first and will be rememeberd for eternity.<br>console.log(add5(3)); // 8</pre><h4>6. Timeouts and Async Execution</h4><p>Closures capture variables from their creation context, making this data available later when asynchronous callbacks eventually execute.</p><pre>function delayedGreeting(name) {<br>  return function() {<br>    console.log(`Hello, ${name}!`);<br>  };<br>}<br><br>setTimeout(delayedGreeting(&quot;John&quot;), 1000); // After 1 Sec: Hello, John! </pre><h4>7. Module Pattern</h4><p>Closures create self-contained code modules with private internal state and selective public interfaces, preventing global namespace pollution.</p><pre>const counter = (function() {<br>  let count = 0;<br>  <br>  return {<br>    increment: () =&gt; ++count,<br>    decrement: () =&gt; --count,<br>    getValue: () =&gt; count,<br>    reset: () =&gt; { count = 0; return count; }<br>  };<br>})();<br><br>counter.increment(); // returns 1<br>counter.increment(); // returns 2<br>counter.getValue(); // returns 2<br>counter.decrement(); // returns 1<br>counter.reset(); // returns 0</pre><p>Here, The counter can’t be accessed directly. We’ve to use the available methods to interact with it.</p><h4>Additional Resources 🎒</h4><ul><li><a href="http://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures">YouDontKnowJS</a></li><li><a href="https://www.youtube.com/watch?v=qikxEIxsXco">Akshay Saini — Namaste JavaScript</a></li><li><a href="https://www.youtube.com/watch?v=aHrvi2zTlaU">ColorCode</a></li><li><a href="https://www.youtube.com/watch?v=6Ixyltr8_R0">Lydia Hallie</a> — Closures Visual Guide.</li></ul><blockquote>Thanks For Reading 💖</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75d8c3177768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript's this keyword: Simple Explanations, Zero Headaches.]]></title>
            <link>https://medium.com/@Abubakkar-Siddhiq/mastering-javascripts-this-keyword-simple-explanations-zero-headaches-e3089af7fea9?source=rss-ecadaa3a6ea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3089af7fea9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Abubakkar Siddhiq]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 04:51:49 GMT</pubDate>
            <atom:updated>2025-02-10T03:06:11.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Uw4Z8pv7VOZ64HnZj--6FQ.png" /><figcaption>what is this? Let’s uncover the mystery together…</figcaption></figure><p><strong><em>this </em></strong><em>is confusing, isn’t it? But no more!</em></p><h3>What is <em>this</em>?</h3><p>Simply put, <strong><em>this </em></strong>is nothing but a guy whose personality changes based on who he’s with. Got an idea? Yeah, that’s our guy <strong><em>this!</em></strong></p><p>Like, People adapt their personalities based on the people they’re with — Just like someone acts differently around their family versus their friends.</p><p>JavaScript’s <strong><em>this </em></strong>behavior also depends on Where and How it’s called! (<em>i.e.,</em> its <strong>call-site). </strong>Its value is determined by where the function is evoked.</p><blockquote><strong>Call-Site: </strong>Location where the function is invoked.<br><strong>Context</strong>: The value of <strong><em>this </em></strong>within a Function.</blockquote><h3>What is Binding?</h3><p>Binding refers to How <strong><em>this </em></strong>gets its value and Where it points to 🧭</p><p>There are <strong>4 main Types of Binding:</strong></p><ul><li><strong>Default Binding</strong></li><li><strong>Implicit Binding</strong></li><li><strong>Explicit Binding</strong></li><li><strong>New Binding</strong></li></ul><h3>Default Binding</h3><p>As the name suggests, It’s by “default” how <strong><em>this </em></strong>behaves.</p><pre>function printThis() {<br>  console.log(this); <br>  // Prints window object in Browser and Global object in node<br>}</pre><h4>Strict vs Non-Strict Mode</h4><p><strong><em>this </em></strong>even behaves differently in Strict and Non-Strict mode. The above code snippet is an example of How <strong><em>this </em></strong>behaves in “Non-Strict mode”.</p><p>But in “Strict mode” the Default value of <strong><em>this </em></strong>becomes undefined. Strict mode was introduced to prevent accidental global scope pollution</p><pre>// Non-Strict Mode<br>function printThis() {<br>  console.log(this); <br>  // Prints window object in Browser and Global object in node<br>}<br><br>// Strict-Mode<br>&quot;use strict&quot;<br>function printThis() {<br>  console.log(this); // undefined<br>}</pre><h3>Implicit Binding and Implicitly Losing it! ⛓️‍💥</h3><p>Implicit Binding occurs when a method has an Object as its context.</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  greet() {<br>    console.log(`Hello, ${this.name}!`)<br>  }<br>}<br><br>user.greet(); // Hello, John!</pre><p>As you can see, <strong><em>this </em></strong>inside the greet()<strong> </strong>function has user object as its context. So we can access anything within that object with <strong><em>this.</em></strong></p><h4>Implicitly Lost</h4><p>How does the Implicitly bound function lose that binding? And once the binding is Lost, <strong><em>this </em></strong>falls back to its “Default Bind”!</p><p>And, Here’s where <strong>Call-Site </strong>matters most. So hang tight, Let’s see How and Why.</p><pre>function greet() {<br>    console.log(`Hello, ${this.name}!`)<br>}<br><br>let user = {<br>  name: &quot;John&quot;,<br>  greet: greet,<br>}<br><br>let greetJohn = user.greet(); <br>// Invoking greet immediately and losing the context!<br><br>let name = &quot;oops, Fell back to global!&quot;; <br>// `name` is now a property of global object<br><br>greetJohn(); // &quot;oops, Fell back to global!&quot;</pre><p>Here in this example, You can see the function greetJohn()<strong> </strong>is just a reference of user.greet()which is a reference of greet()<strong>. </strong>And this is where <strong>Call-Site </strong>matters. The call-site is now greetJohn(), and since it’s no longer called as a method of user, <strong><em>this </em></strong>falls back to the global object.</p><p>The most common and unexpected way this can happen is when we pass a <strong>Call-Back</strong> Function.</p><pre>function hello() {<br>  console.log(`Hello! , ${this.name}`);<br>}<br><br>function sayHello() {<br>  hello();<br>}<br><br>let user = {<br>  name: &quot;John&quot;,<br>  greet: hello,<br>}<br><br>let name = &quot;Dang! We&#39;re at global again..&quot;<br><br>sayHello(user.greet); // &quot;Dang! We&#39;re at global again..&quot;</pre><p>Since you know the <strong>Call-Site </strong>is what matters, How hello()&#39;s Context will be set to user object if it&#39;s called inside sayHello() ? Huh? Make sense now? It should!</p><h3>Explicit Binding and Binding it Hard! 💝</h3><p>Explicit Binding is when we manually specify what the context of <strong><em>this </em></strong>should be. We can explicitly bind using three JavaScript’s built-in methods:</p><h4>1. Call Method</h4><p>function.call(object, arg1, arg2, …) This method takes an object as its first argument and other arguments are for the function you’re binding it with.</p><pre>function intro(age, city) {<br>  console.log(`Hi, I&#39;m ${this.name}, ${age} from ${city}`);<br>}<br><br>const guy = { name: &quot;Peter&quot; };<br><br>intro.call(guy, 71, &quot;Chennai&quot;); // I&#39;m Peter, 71 from Chennai<br></pre><h4>2. Apply Method</h4><p>function.apply(object, [arg1, arg2, …]) It’s the same as <strong>call</strong> but takes arguments in an Array.</p><pre>function intro(age, city) {<br>  console.log(`Hi, I&#39;m ${this.name}, ${age} from ${city}`);<br>}<br><br>const guy = { name: &quot;Peter&quot; };<br><br>intro.apply(guy, [21, &quot;Chennai&quot;]); // I&#39;m Peter, 21 from Chennai</pre><h4>3. HARD Binding — The Bind Method</h4><p>Unlike Apply and Call, The bind method doesn’t invoke the function immediately. Rather, It creates a new function with fixed <strong><em>this</em></strong>. And, it’s the <strong>hardest </strong>form of binding which can’t be overridden! (But we can override it with <strong>New binding</strong>).</p><pre>function intro() {<br>  console.log(`Hi, I&#39;m ${this.name});<br>}<br><br>const guy  = { name: &quot;Peter&quot; };<br>const guy1 = { name: &quot;Joe&quot; };<br>const guy2 = { name: &quot;Tom&quot; };<br><br>const giveIntro = intro.bind(guy); <br>giveIntro();  // Hi, I&#39;m Peter<br><br>// Can&#39;t be overriden see 👇<br>giveIntro.call(guy1);  // Hi, I&#39;m Peter<br>giveIntro.apply(guy1); // Hi, I&#39;m Peter</pre><p>when a function is hardbound 🔗, It stays loyal to its object to which it is bound to 😍 Unless <strong>New-Binding </strong>comes in-between and overrides it 💔</p><h3>New Binding</h3><p>Don’t let the name fool you. It’s not some new mind-bending technique that came to destroy all the other bindings. In fact, if you’re coming from other programming languages this is the only binding we’re used to. But, here in JS it’s kinda different.</p><p>New Binding occurs when a function is called with new keyword. This binding follows the following steps:</p><ol><li>It creates a new object out of the blue.</li><li>Link the object’s prototype <em>[[Prototype]]</em></li><li>Set <strong><em>this </em></strong>to the new object</li><li>Returns the object automatically.</li></ol><pre>function User(name) {<br>    // &#39;this&#39; is automatically bound to new object<br>    this.name = name;<br>    this.greet = function() {<br>        console.log(`Hello, ${this.name}`);<br>    };<br>}<br><br>const user = new User(&#39;John&#39;);<br>user.greet(); // &quot;Hello, John&quot;</pre><p>Yeah, Pretty much like Class and Constructors. Also note: If your function has a return statement that is primitive, It’ll be ignored.</p><pre>function Person(name) {<br>  this.name = name;<br>  return &quot;Plz don&#39;t ignore me 🥺&quot;;  // This return value is ignored 😁<br>}<br><br>const person1 = new Person(&#39;Alice&#39;);<br><br>console.log(person1.name);  // Logs &quot;Alice&quot;, because `this` refers to the new object<br>console.log(person1);       // Logs the new object: Person { name: &#39;Alice&#39; }</pre><h3><strong><em>this </em></strong>in Arrow-Functions 🏹</h3><p>Arrow functions won’t respond to this as normal functions. The context of <strong><em>this </em></strong>in a Arrow-Function is its Lexical-Scope’s <strong><em>this.</em></strong></p><pre>const obj = {<br>  name: &quot;Martin&quot;,<br>  greet: () =&gt; {<br>    console.log(this.name); // &#39;this&#39; is inherited from the outer scope obj&#39;s this<br>  }<br>};<br>obj.greet(); // window/global/undefined (because `this` is not referring to `obj` inside the arrow function)</pre><p>To be more clear,</p><pre>const obj = {<br>  name: &quot;Martin&quot;,<br>  greet: function() {<br>    const arrowFunc = () =&gt; {<br>      console.log(this.name); // &#39;this&#39; is now greet&#39;s this which is obj.<br>    };<br>    arrowFunc();<br>  }<br>};<br><br>obj.greet(); // &quot;Martin&quot;</pre><h3>this inside DOM Elements 🏗️</h3><p>Inside the DOM, <strong><em>this </em></strong>refers to the Element itself.</p><pre>const button = document.querySelector(&#39;button&#39;);<br>button.addEventListener(&#39;click&#39;, function() {<br>  console.log(this); // &#39;this&#39; refers to the button element<br>});</pre><blockquote>That’s it! If you’ve read till here. Thank You so much! 💖</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3089af7fea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>