<?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 Bashira Farhin on Medium]]></title>
        <description><![CDATA[Stories by Bashira Farhin on Medium]]></description>
        <link>https://medium.com/@farhinbashira?source=rss-8d2e3a58af0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0WWYm0sCoJVhURHs1UzESA.jpeg</url>
            <title>Stories by Bashira Farhin on Medium</title>
            <link>https://medium.com/@farhinbashira?source=rss-8d2e3a58af0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:29:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farhinbashira/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[Understanding AWS Cost and Usage Report (CUR)]]></title>
            <link>https://aws.plainenglish.io/understanding-aws-cost-and-usage-report-cur-c95559cee1fe?source=rss-8d2e3a58af0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95559cee1fe</guid>
            <category><![CDATA[cost-and-usage-report]]></category>
            <category><![CDATA[aws-reserved-instances]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[savings-plan]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Bashira Farhin]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 06:48:59 GMT</pubDate>
            <atom:updated>2026-08-23T18:50:52.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XEaDcc-4LSKGu40O" /><figcaption>Photo by <a href="https://unsplash.com/@shotbywoliul?utm_source=medium&amp;utm_medium=referral">Woliul Hasan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AWS <strong>Cost and Usage Report (CUR)</strong> is a detailed report that contains information about your AWS resource usage and the costs associated with that usage.</p><p>Think of CUR as a large table where each row represents a charge or usage record, and each column provides specific information about that record, such as:</p><ul><li>Which AWS service was used (for example, EC2, S3, Lambda)</li><li>When the resource was used (usage start and end time)</li><li>How much of the resource was consumed (usage quantity)</li><li>The cost associated with that usage</li><li>The AWS account that incurred the cost</li><li>Billing, pricing, and discount details related to the usage</li></ul><p>This documentation explains key columns from <strong>CUR 1.0</strong>(and not CUR 2.0) and focuses only on beginner-relevant fields; some product-level columns are intentionally omitted as they are not necessary at this stage, and split cost line item details are also excluded for simplicity.</p><p>Example CUR</p><pre>┌─────────┬──────────────────────┬────────┐<br>│ Service │ Usage                │ Cost   │<br>├─────────┼──────────────────────┼────────┤<br>│ EC2     │ 100 instance hours   │ $12.50 │<br>│ S3      │ 250 GB storage       │ $5.75  │<br>│ Lambda  │ 1,000,000 requests   │ $2.30  │<br>└─────────┴──────────────────────┴────────┘</pre><p>The actual CUR contains many more columns, but each row follows this same idea, it records one billing or usage event.</p><p><strong>Why do we need CUR?</strong></p><p>CUR provides the detailed billing data needed to analyze AWS spending. It helps answer questions such as:</p><ul><li>Which AWS services are being used</li><li>How much each service costs</li><li>Which AWS account or project generated the cost</li><li>How spending has changed over time</li><li>Which resources contribute the most to the monthly bill</li><li>How AWS costs can be optimized</li></ul><p>Since CUR contains the most detailed billing information provided by AWS, it is widely used for cost analysis, reporting, budgeting, dashboards, and cost optimization.</p><h3>CUR Columns</h3><ul><li>Identity details</li><li>Billing details</li><li>Line item details</li><li>Reservation details</li><li>Pricing details</li><li>Product details</li><li>Resource tags details</li><li>Savings Plans details</li><li>Cost Categories details</li><li>Discount details</li><li>Split line item details</li></ul><p><strong>Note:</strong></p><p>Every Cost and Usage Report includes <strong>Identity</strong>, <strong>Bill</strong>, and <strong>LineItem</strong> columns. These fields are also known as <strong>static fields</strong> because they appear in every CUR.</p><p>All other columns are included in your report only if your monthly AWS usage generates data to populate those columns.</p><p>For example, if you have taken a Savings Plan, only then will the columns related to Savings Plan details appear in your CUR.</p><p>Each row in a CUR table is called a <strong>line item</strong>.</p><h3>Identity Details</h3><p>Identity line item columns are used in the report to find specific line items that have been split across multiple AWS CUR files.</p><h4>Why does AWS split CUR into multiple files?</h4><p>Imagine your organization has:</p><ul><li>500 AWS accounts</li><li>Millions of EC2, S3, Lambda, and RDS usage records every day</li></ul><p>For the month of May, the CUR might contain <strong>200 million rows</strong>. Storing all of these rows in a single file would make the file extremely large and difficult to process efficiently.</p><p>Instead, AWS generates multiple files, for example:</p><pre>2026-05/<br>├── part-00001.parquet<br>├── part-00002.parquet<br>├── part-00003.parquet<br>└── part-00004.parquet</pre><p>Together, these files make up the complete CUR for May.</p><h3>Identity Columns</h3><ul><li>identity/LineItemId</li><li>identity/TimeInterval</li></ul><h4>identity/LineItemId</h4><p>This field is generated for each line item and is unique in a given partition.</p><p>identity/LineItemId is an ID assigned by AWS to each line item when a CUR report is generated.</p><p>It helps uniquely identify a line item within that specific CUR delivery, but it is <strong>not a permanent ID</strong>.</p><p>Example 1: Same report split into multiple files</p><p>Suppose AWS generates the CUR for <strong>November 29</strong>. Because the report is large, it is split into two files.</p><p>part-00001.parquet</p><pre>┌────────────┬──────────┬──────┐<br>│ LineItemId │ Resource │ Cost │<br>├────────────┼──────────┼──────┤<br>│ 1001       │ EC2-A    │ $10  │<br>│ 1002       │ S3       │ $5   │<br>└────────────┴──────────┴──────┘</pre><p>part-00002.parquet</p><pre>┌────────────┬──────────┬──────┐<br>│ LineItemId │ Resource │ Cost │<br>├────────────┼──────────┼──────┤<br>│ 1003       │ Lambda   │ $2   │<br>│ 1004       │ EC2-B    │ $8   │<br>└────────────┴──────────┴──────┘</pre><p>Notice that every row has a unique <strong>LineItemId</strong>.</p><p>Even though the report is split into two files, AWS guarantees that within this November 29 report, no two rows will have the same <strong>LineItemId</strong>.</p><p>Example 2: Next day’s report</p><p>On <strong>November 30</strong>, AWS generates a new CUR.</p><p>It contains the same EC2 instance (<strong>EC2-A</strong>) because it is still running.</p><p>November 30 CUR</p><pre>┌────────────┬──────────┬──────┐<br>│ LineItemId │ Resource │ Cost │<br>├────────────┼──────────┼──────┤<br>│ 2501       │ EC2-A    │ $10  │<br>│ 2502       │ S3       │ $5   │<br>│ 2503       │ Lambda   │ $2   │<br>└────────────┴──────────┴──────┘</pre><p><strong>Note:</strong></p><ul><li>The resource is the same, but the <strong>LineItemId</strong> has changed.</li><li>The <strong>LineItemId</strong> isn’t consistent between different Cost and Usage Reports.</li><li>You cannot use <strong>LineItemId</strong> to track the same resource across different CUR deliveries.</li></ul><h4>identity/TimeInterval</h4><p>represents the time range during which the usage or charge in that row occurred. It is a combination of <strong>UsageStartDate/UsageEndDate</strong></p><pre>YYYY-MM-DDTHH:mm:ssZ/YYYY-MM-DDTHH:mm:ssZ</pre><p>The time interval is in UTC and can be either <strong>daily</strong> or <strong>hourly</strong>, depending on the granularity of the report.</p><p>Example</p><p>Hourly CUR</p><pre>2017-11-01T00:00:00Z/2017-11-01T01:00:00Z</pre><p>Includes only 1 hour <strong>(00:00–01:00)</strong>.</p><p>Daily CUR</p><pre>2017-11-01T00:00:00Z/2017-11-02T00:00:00Z</pre><p>Includes the full day of November 1, 2017.</p><h3>Billing Details</h3><p>You can use the billing line item columns in the report to find details about the specific bill covered by the report, such as the charge type and the beginning and end of the billing period.</p><h4>Billing Columns</h4><ul><li>bill/BillingEntity</li><li>bill/BillingPeriodStartDate</li><li>bill/BillingPeriodEndDate</li><li>bill/BillType</li><li>bill/InvoiceId</li><li>bill/InvoicingEntity</li><li>bill/PayerAccountId</li></ul><h4>bill/BillingEntity</h4><p>Helps you identify whether your invoices or transactions are for <strong>AWS Marketplace</strong> or for purchases of other AWS services.</p><p>Possible values include:</p><ul><li><strong>AWS</strong> — Identifies a transaction for AWS services other than AWS Marketplace.</li><li><strong>AWS Marketplace</strong> — Identifies a purchase in AWS Marketplace.</li></ul><p>This makes it easy to separate cloud infrastructure costs from third-party software and subscriptions when analyzing your AWS bill.</p><p>Example</p><p>You launch an EC2 instance. The service is provided directly by AWS.</p><p>Therefore:</p><pre>bill/BillingEntity = AWS</pre><p>Suppose you launch an EC2 instance with a paid firewall software from the AWS Marketplace.</p><p>The firewall software is sold through AWS Marketplace, so it is marked as an AWS Marketplace charge.</p><pre>┌──────────────────────────┬───────────────────┬──────┐<br>│ Service                  │ bill/BillingEntity│ Cost │<br>├──────────────────────────┼───────────────────┼──────┤<br>│ Amazon EC2               │ AWS               │ $20  │<br>│ Firewall Software License│ AWS Marketplace   │ $8   │<br>└──────────────────────────┴───────────────────┴──────┘</pre><h4>bill/BillingPeriodStartDate</h4><p>The start date of the billing period covered by the CUR, inclusive.</p><p>It is stored in UTC and is in the format:</p><pre>YYYY-MM-DDTHH:mm:ssZ</pre><h4>bill/BillingPeriodEndDate</h4><p>The end date of the billing period covered by the CUR, exclusive .</p><p>It is stored in UTC and is in the format:</p><pre>YYYY-MM-DDTHH:mm:ssZ</pre><p>Why are these columns useful?</p><p>These columns indicate <strong>which billing month a charge belongs to</strong>.</p><p>They identify the billing period in which AWS included the charge, regardless of when the resource was actually used.</p><p>For a single monthly CUR, every row has the same <strong>bill/BillingPeriodStartDate</strong> and <strong>bill/BillingPeriodEndDate</strong> values because all line items belong to the same billing period.</p><p>Example 1: CUR for May 2026</p><pre>┌─────────────────────────┬─────────────────────────┬──────────────────────┬─────────┬──────┐<br>│ BillingPeriodStartDate  │ BillingPeriodEndDate    │ UsageStartDate       │ Service │ Cost │<br>├─────────────────────────┼─────────────────────────┼──────────────────────┼─────────┼──────┤<br>│ 2026-05-01 00:00:00     │ 2026-06-01 00:00:00     │ 2026-05-02 10:15:00  │ EC2     │ $10  │<br>│ 2026-05-01 00:00:00     │ 2026-06-01 00:00:00     │ 2026-05-18 08:30:00  │ S3      │ $5   │<br>│ 2026-05-01 00:00:00     │ 2026-06-01 00:00:00     │ 2026-05-30 21:45:00  │ Lambda  │ $2   │<br>└─────────────────────────┴─────────────────────────┴──────────────────────┴─────────┴──────┘</pre><p><strong>Note:</strong></p><p>These columns indicate the billing period (invoice) in which AWS billed the charge, regardless of when the resource was actually used.</p><h4>bill/BillType</h4><p>The type of bill that this report covers.</p><p>There are three bill types:</p><ul><li><strong>Anniversary</strong> — Line items for services that you used during the month.</li><li><strong>Purchase</strong> — Line items for upfront service fees.</li><li><strong>Refund</strong> — Line items for refunds.</li></ul><h4>1. Anniversary</h4><p>Contains charges for the AWS services you used during the billing period.</p><p>Example</p><p>Suppose during May you used:</p><ul><li>EC2 instances</li><li>S3 storage</li><li>Lambda functions</li></ul><p>Your CUR may contain:</p><pre>┌──────────────┬─────────┬──────┐<br>│ BillType     │ Service │ Cost │<br>├──────────────┼─────────┼──────┤<br>│ Anniversary  │ EC2     │ $120 │<br>│ Anniversary  │ S3      │ $35  │<br>│ Anniversary  │ Lambda  │ $12  │<br>└──────────────┴─────────┴──────┘</pre><p><strong>Note:</strong> These are your normal monthly usage charges.</p><h4>2. Purchase</h4><p>Contains one-time upfront charges for purchases.</p><p>This usually occurs when you buy services that require an upfront payment, such as:</p><ul><li>Reserved Instances with an upfront payment</li><li>Savings Plans with an upfront payment</li><li>AWS Marketplace software with an upfront fee</li></ul><p>Example</p><p>Suppose you purchase a <strong>1-year All Upfront Reserved Instance</strong> for <strong>$1,200</strong>.</p><p>Your CUR may contain:</p><pre>┌──────────┬──────────────────────────────────┬────────┐<br>│ BillType │ Service                          │ Cost   │<br>├──────────┼──────────────────────────────────┼────────┤<br>│ Purchase │ EC2 Reserved Instance Upfront Fee│ $1,200 │<br>└──────────┴──────────────────────────────────┴────────┘</pre><p><strong>Note:</strong> This is <strong>not</strong> a monthly usage charge, it is a <strong>one-time purchase</strong>.</p><h4>3. Refund</h4><p>Contains credits or refunds issued by AWS.</p><p>Refunds may occur if:</p><ul><li>AWS issues a billing correction.</li><li>You receive a refund for an AWS Marketplace purchase.</li><li>AWS grants a service credit.</li></ul><p>Example</p><p>Suppose AWS accidentally charged you twice and later refunds <strong>$25</strong>.</p><p>Your CUR may contain:</p><pre>┌──────────┬────────────────────┬──────┐<br>│ BillType │ Description        │ Cost │<br>├──────────┼────────────────────┼──────┤<br>│ Refund   │ Billing Adjustment │ -$25 │<br>└──────────┴────────────────────┴──────┘</pre><p><strong>Note:</strong> The cost is <strong>negative</strong> because AWS is returning money to you.</p><h4>bill/InvoiceId</h4><p>The Invoice ID associated with a specific line item.</p><p>Until the report is final, the <strong>InvoiceId</strong> is blank.</p><p>Example</p><p>Suppose it is <strong>May 20</strong>, and AWS is still generating the May bill.</p><pre>┌───────────┬─────────┬──────┐<br>│ InvoiceId │ Service │ Cost │<br>├───────────┼─────────┼──────┤<br>│ (blank)   │ EC2     │ $15  │<br>│ (blank)   │ S3      │ $8   │<br>└───────────┴─────────┴──────┘</pre><p><strong>Note:</strong> The invoice has <strong>not yet been finalized</strong>.</p><p>After the billing period ends, AWS finalizes the invoice.</p><pre>┌────────────────────┬─────────┬──────┐<br>│ InvoiceId          │ Service │ Cost │<br>├────────────────────┼─────────┼──────┤<br>│ INV-2026-05-123456 │ EC2     │ $15  │<br>│ INV-2026-05-123456 │ S3      │ $8   │<br>└────────────────────┴─────────┴──────┘</pre><p><strong>Note:</strong> Both line items belong to the same invoice, so they have the same <strong>InvoiceId</strong>.</p><p>A single month can have multiple InvoiceId values in cases such as:</p><ul><li>Different invoicing entities.</li><li>AWS Marketplace purchases that are invoiced separately.</li><li>Refund or credit invoices.</li><li>Certain tax or regional invoicing scenarios.</li></ul><h4>bill/InvoicingEntity</h4><p>The AWS entity that issues the invoice.</p><p>Possible values include:</p><ul><li><strong>Amazon Web Services, Inc.</strong> — The entity that issues invoices to customers globally, where applicable.</li><li><strong>Amazon Web Services India Private Limited</strong> — The entity that issues invoices to customers based in India.</li><li><strong>Amazon Web Services South Africa Proprietary Limited</strong> — The entity that issues invoices to customers in South Africa.</li></ul><p>bill/BillingEntity — Who provided the AWS service/product being charged?<br>bill/InvoicingEntity — Which AWS entity issued the invoice for the charge?</p><h4>bill/PayerAccountId</h4><p>The account ID of the paying account.</p><p>For an organization in <strong>AWS Organizations</strong>, this is the account ID of the <strong>management (payer) account</strong>.</p><ul><li>If you have a standalone AWS account, this is your own account ID.</li><li>If you use AWS Organizations, this is the management (payer) account ID, even if the resources were used by different member accounts.</li></ul><p>Example 1: Standalone Account</p><p>Suppose you have a single AWS account.</p><pre>┌──────────────────┬───────────────┬─────────┬──────┐<br>│ PayerAccountId   │ UsageAccountId│ Service │ Cost │<br>├──────────────────┼───────────────┼─────────┼──────┤<br>│ 111111111111     │ 111111111111  │ EC2     │ $25  │<br>└──────────────────┴───────────────┴─────────┴──────┘</pre><p>Since there is only one account, both the <strong>PayerAccountId</strong> and <strong>UsageAccountId</strong> are the same.</p><p>Example 2: AWS Organizations</p><p>Suppose your organization has the following structure:</p><pre>111111111111 (Management / Payer Account)<br>│<br>├── 222222222222 (Development)<br>├── 333333333333 (Production)<br>└── 444444444444 (Testing)</pre><p>The CUR may contain:</p><pre>┌──────────────────┬────────────────┬─────────┬──────┐<br>│ PayerAccountId   │ UsageAccountId │ Service │ Cost │<br>├──────────────────┼────────────────┼─────────┼──────┤<br>│ 111111111111     │ 222222222222   │ EC2     │ $100 │<br>│ 111111111111     │ 333333333333   │ S3      │ $80  │<br>│ 111111111111     │ 444444444444   │ Lambda  │ $15  │<br>└──────────────────┴────────────────┴─────────┴──────┘</pre><p>Notice that the <strong>PayerAccountId</strong> is the same for every row because the management account pays the bill for all member accounts.</p><p>The <strong>UsageAccountId</strong> identifies which member account actually used the AWS resources.</p><p><strong>Note:</strong></p><ul><li><strong>PayerAccountId</strong> tells you <strong>who pays the bill</strong>.</li><li><strong>UsageAccountId</strong> tells you <strong>who used the resources</strong>.</li></ul><h3>Line Item Details</h3><p>Line item details cover all of the cost and usage information for your AWS usage.</p><h4>Line Item Columns</h4><ul><li>lineItem/AvailabilityZone</li><li>lineItem/BlendedCost</li><li>lineItem/BlendedRate</li><li>lineItem/CurrencyCode</li><li>lineItem/LegalEntity</li><li>lineItem/LineItemDescription</li><li>lineItem/LineItemType</li><li>lineItem/UsageAmount</li><li>lineItem/UnblendedRate</li><li>lineItem/UnblendedCost</li><li>lineItem/NetUnblendedRate</li><li>lineItem/NetUnblendedCost</li><li>lineItem/NormalizationFactor</li><li>lineItem/NormalizedUsageAmount</li><li>lineItem/Operation</li><li>lineItem/ProductCode</li><li>lineItem/ResourceId</li><li>lineItem/TaxType</li><li>lineItem/UsageAccountId</li><li>lineItem/UsageStartDate</li><li>lineItem/UsageEndDate</li><li>lineItem/UsageType</li></ul><h4>lineItem/AvailabilityZone</h4><p>The Availability Zone that hosts this line item.</p><p>For example:</p><ul><li>us-east-1a</li><li>us-east-1b</li></ul><h4>lineItem/BlendedCost</h4><p>The BlendedRate multiplied by the UsageAmount.</p><p>Formula:</p><pre>BlendedCost = BlendedRate × UsageAmount<br>where<br>BlendedRate  = Average cost per unit<br>UsageAmount  = Number of units used<br>BlendedCost  = Allocated cost using the blended rate</pre><p><strong>Note:</strong></p><p>BlendedCost is blank for line items that have a <strong>LineItemType</strong> of <strong>Discount</strong>.</p><p>Discounts are calculated using only the unblended cost of a member account, aggregated by member account and SKU.</p><p>As a result, BlendedCost is not available for discounts.</p><h4><strong>lineItem/BlendedRate</strong></h4><p>The <strong>BlendedRate</strong> is the average cost incurred for each SKU across an AWS Organization.</p><h4>What is a Blended Rate?</h4><p>A Blended Rate is an average price per unit of usage calculated across all member accounts in an AWS Organization.</p><p>Instead of charging each member account exactly what it individually paid, AWS calculates a single average rate and uses that to allocate costs.</p><p>For a standalone account, the blended rate is the same as the actual rate because the average of a single price is the price itself.</p><p>Why were blended rates introduced?</p><ul><li>Blended rates were introduced to simplify cost allocation across member accounts.</li><li>Instead of one account receiving all the benefit of a Reserved Instance or volume discount, AWS spreads the discount across the organization.</li><li>Nowadays, many customers prefer <strong>UnblendedCost</strong> or <strong>NetUnblendedCost</strong> because they reflect the actual charges incurred by each account.</li></ul><p>Example</p><p>Imagine a company has multiple AWS accounts.</p><pre>Company<br>│<br>├── Dev Account<br>├── Test Account<br>└── Production Account</pre><p>Suppose the On-Demand pricing is:</p><ul><li>First 100 hours = $1.00/hour</li><li>Next 100 hours = $0.80/hour (volume discount)</li></ul><p>Total organization usage = <strong>200 hours</strong></p><p>Actual AWS bill:</p><ul><li>100 × $1.00 = $100</li><li>100 × $0.80 = $80</li><li><strong>Total = $180</strong></li></ul><p>Blended Rate: $180 ÷ 200 = $0.90/hour</p><pre>┌─────────┬───────┬─────────────────┬──────────────┐<br>│ Account │ Hours │ Unblended Cost  │ Blended Cost │<br>├─────────┼───────┼─────────────────┼──────────────┤<br>│ Dev     │ 50    │ $50($50 * $1)   │ $45(0.9*50)  │<br>│ Test    │ 50    │ $50($50 * $1)   │ $45(0.9*50)  │<br>│ Prod    │ 100   │ $80($100 * $0.8)│ $90(0.9*100) │<br>├─────────┼───────┼─────────────────┼──────────────┤<br>│ Total   │ 200   │ $180            │ $180         │<br>└─────────┴───────┴─────────────────┴──────────────┘</pre><ul><li><strong>Unblended Cost:</strong> Shows the actual cost charged to each account. The account that received the volume discount (Prod) gets the lower cost.</li><li><strong>Blended Cost:</strong> Distributes the total bill across all accounts using the average rate ($0.90/hour), so every account pays the same rate per hour.</li></ul><h4>lineItem/CurrencyCode</h4><p>The currency that this line item is shown in.</p><p>All AWS customers are billed in <strong>US dollars (USD)</strong> by default.</p><p>To change your billing currency, see the AWS Billing User Guide.</p><h4>lineItem/LegalEntity</h4><p>The Seller of Record of a specific product or service.</p><p>In most cases, the <strong>InvoicingEntity</strong> and <strong>LegalEntity</strong> are the same.</p><p>The values might differ for third-party AWS Marketplace transactions.</p><p>Possible values include:</p><ul><li><strong>Amazon Web Services, Inc.</strong> — The entity that sells AWS services.</li><li><strong>Amazon Web Services India Private Limited</strong> — The local Indian entity that acts as a reseller for AWS services in India.</li></ul><h4>lineItem/LineItemDescription</h4><p>Describes what the line item represents.</p><p>It provides a human-readable description of the usage, fee, discount, or other charge associated with the line item.</p><p>Example: EC2 On-Demand Usage</p><p>You run an EC2 instance for <strong>10 hours</strong>.</p><pre>┌──────────────────────────────┬──────────────────────────────────────────────┐<br>│ Column                       │ Value                                        │<br>├──────────────────────────────┼──────────────────────────────────────────────┤<br>│ lineItem/LineItemType        │ Usage                                        │<br>│ lineItem/LineItemDescription │ Running On-Demand Linux m5.large instance    │<br>└──────────────────────────────┴──────────────────────────────────────────────┘</pre><p>The description tells you what usage generated the charge.</p><h4>lineItem/LineItemType</h4><p>lineItem/LineItemType identifies the type of charge represented by the line item.</p><p>The possible values are:</p><ol><li>Usage</li><li>DiscountedUsage</li><li>Fee</li><li>RIFee</li><li>SavingsPlanUpfrontFee</li><li>SavingsPlanRecurringFee</li><li>SavingsPlanCoveredUsage</li><li>SavingsPlanNegation</li><li>Credit</li><li>Discount</li><li>BundledDiscount</li><li>Refund</li><li>Tax</li><li>FlatRateSubscription</li></ol><p><strong>1. Usage</strong></p><p>Describes that the charge associated with this line item is regular pay-as-you-go (On-Demand) usage charges.</p><pre>┌──────────────┬─────────┬──────────┬───────┐<br>│ LineItemType │ Service │ Usage    │ Cost  │<br>├──────────────┼─────────┼──────────┼───────┤<br>│ Usage        │ EC2     │ 10 hours │ $1.00 │<br>└──────────────┴─────────┴──────────┴───────┘</pre><p><strong>2. DiscountedUsage</strong></p><p>Describes that the charge associated with this line item received Reserved Instance (RI) pricing instead of On-Demand pricing.</p><p>Example</p><p>Assume:</p><ul><li>On-Demand price = <strong>$0.10/hour</strong></li><li>Reserved Instance price = <strong>$0.04/hour</strong></li><li>EC2 instance runs for <strong>10 hours</strong></li></ul><pre>┌───────────────────┬─────────────────────┬─────────────────────┐<br>│ LineItemType      │ On-Demand Cost      │ Cost Charged        │<br>├───────────────────┼─────────────────────┼─────────────────────┤<br>│ Usage             │ 10 × $0.10 = $1.00  │ $1.00               │<br>│ DiscountedUsage   │ 10 × $0.10 = $1.00  │ 10 × $0.04 = $0.40  │<br>└───────────────────┴─────────────────────┴─────────────────────┘</pre><p><strong>3. Fee</strong></p><p>Describes that the charge associated with this line item is a one-time upfront payment.</p><p>Usually appears when purchasing:</p><ul><li>All Upfront Reserved Instances</li><li>Partial Upfront Reserved Instances</li></ul><p>Example</p><p>You buy a <strong>1-year All Upfront RI</strong> for <strong>$1,200</strong>.</p><pre>┌──────────────┬─────────────────┬────────┐<br>│ LineItemType │ Description     │ Cost   │<br>├──────────────┼─────────────────┼────────┤<br>│ Fee          │ RI Upfront Fee  │ $1,200 │<br>└──────────────┴─────────────────┴────────┘</pre><p><strong>4. RIFee</strong></p><p>Describes that the charge associated with this line item is the monthly recurring fee for Reserved Instances.</p><p>Applies mainly to:</p><ul><li>Partial Upfront RI</li><li>No Upfront RI</li></ul><p>For <strong>All Upfront RIs</strong>, this row still exists, but the recurring charge is usually <strong>$0</strong>.</p><p>Example</p><pre>┌──────────────┬────────────────┬──────┐<br>│ LineItemType │ Description    │ Cost │<br>├──────────────┼────────────────┼──────┤<br>│ RIFee        │ Monthly RI Fee │ $30  │<br>└──────────────┴────────────────┴──────┘</pre><p><strong>5. SavingsPlanUpfrontFee</strong></p><p>Describes that the charge associated with this line item is a one-time upfront payment when purchasing a Savings Plan.</p><p>6. <strong>SavingsPlanRecurringFee</strong></p><pre>┌──────────────────────────────────────────────┬────────────────────────────────────────────────────────────┐<br>│ Payment option                               │ SavingsPlanRecurringFee meaning                            │<br>├──────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤<br>│ All Upfront                                  │ Unused portion of the Savings Plan commitment              │<br>│                                              │ during the billing period                                  │<br>│ Partial Upfront                              │ Recurring hourly charge                                    │<br>│ No Upfront                                   │ Recurring hourly charge                                    │<br>└──────────────────────────────────────────────┴────────────────────────────────────────────────────────────┘</pre><p>Example</p><p>You buy a <strong>1-year Partial Upfront Savings Plan</strong>.</p><pre>┌────────────────────────────┬──────┐<br>│ LineItemType               │ Cost │<br>├────────────────────────────┼──────┤<br>│ SavingsPlanRecurringFee    │ $100 │<br>└────────────────────────────┴──────┘</pre><p><strong>7. SavingsPlanCoveredUsage</strong></p><p>Describes that the charge associated with this line item is the usage that was covered by your Savings Plan</p><p>Example</p><pre>┌────────────────────────────┬──────┐<br>│ LineItemType               │ Cost │<br>├────────────────────────────┼──────┤<br>│ SavingsPlanCoveredUsage    │ $40  │<br>└────────────────────────────┴──────┘</pre><p><strong>8. SavingsPlanNegation</strong></p><p>Describes that the charge associated with this line item is the negation of the corresponding <strong>SavingsPlanCoveredUsage</strong>.</p><p>Example</p><pre>┌────────────────────────────┬──────┐<br>│ LineItemType               │ Cost │<br>├────────────────────────────┼──────┤<br>│ SavingsPlanCoveredUsage    │ $40  │<br>│ SavingsPlanNegation        │ -$40 │<br>└────────────────────────────┴──────┘</pre><p><strong>9. Credit</strong></p><p>Describes that the charge associated with this line item is free credits AWS applies to your account.</p><p>Examples:</p><ul><li>Promotional credits</li><li>Support credits</li><li>Service credits</li></ul><p>Example</p><p>AWS gives you a <strong>$100 promotional credit</strong>.</p><pre>┌──────────────┬───────┐<br>│ LineItemType │ Cost  │<br>├──────────────┼───────┤<br>│ Credit       │ -$100 │<br>└──────────────┴───────┘</pre><p><strong>10. Discount</strong></p><p>Describes that the charge associated with this line item is discounts directly applied by AWS.</p><p>Examples:</p><ul><li>Enterprise Discount Program (EDP)</li><li>Contract discounts</li><li>Other negotiated discounts</li></ul><p>Example</p><pre>┌──────────────┬──────┐<br>│ LineItemType │ Cost │<br>├──────────────┼──────┤<br>│ Usage        │ $500 │<br>│ Discount     │ -$50 │<br>└──────────────┴──────┘</pre><p><strong>11. BundledDiscount</strong></p><p>Describes that the charge associated with this line item is a discount automatically applied because you’re already using another AWS service.</p><p>Example</p><p>Suppose AWS offers:</p><p>Use Amazon CloudFront and receive 100 GB of free data transfer from Amazon S3.</p><p>Your CUR may contain:</p><pre>┌──────────────────┬────────────────────┬──────┐<br>│ LineItemType     │ Description        │ Cost │<br>├──────────────────┼────────────────────┼──────┤<br>│ Usage            │ S3 Data Transfer   │ $15  │<br>│ BundledDiscount  │ CloudFront Benefit │ -$15 │<br>└──────────────────┴────────────────────┴──────┘</pre><p><strong>12. Refund</strong></p><p>Describes that the charge associated with this line item is money returned by AWS.</p><p>Usually due to:</p><ul><li>Billing correction</li><li>Service issue</li><li>Marketplace refund</li></ul><p>Example:</p><pre>┌──────────────┬──────┐<br>│ LineItemType │ Cost │<br>├──────────────┼──────┤<br>│ Refund       │ -$20 │<br>└──────────────┴──────┘</pre><p><strong>13. Tax</strong></p><p>Describes that the charge associated with this line item is taxes added to your bill.</p><p>Examples:</p><ul><li>GST</li><li>VAT</li><li>US Sales Tax</li></ul><p>Example</p><pre>┌──────────────┬──────┐<br>│ LineItemType │ Cost │<br>├──────────────┼──────┤<br>│ Usage        │ $100 │<br>│ Tax          │ $18  │<br>└──────────────┴──────┘</pre><p><strong>14. FlatRateSubscription</strong></p><p>Describes that the charge associated with this line item is a recurring subscription fee for services that charge a fixed subscription rather than usage-based pricing.</p><p>Example</p><p>Suppose a service charges:</p><ul><li>Enterprise Subscription</li><li>$200/month</li></ul><p>CUR:</p><pre>┌──────────────────────┬──────┐<br>│ LineItemType         │ Cost │<br>├──────────────────────┼──────┤<br>│ FlatRateSubscription │ $200 │<br>└──────────────────────┴──────┘</pre><p>Unlike EC2 or S3, the fee does not depend on hours, storage, or requests. It is simply the fixed subscription charge for the billing period.</p><h4>lineItem/UsageAmount</h4><p>Describes the quantity of resource consumed for the line item.</p><p>The unit depends on the AWS service. For example:</p><ul><li>Hours (EC2)</li><li>GB-Month (S3 Storage)</li><li>Requests (S3 API)</li><li>GB (Data Transfer)</li><li>Seconds (Lambda)</li></ul><p>It only tells <strong>how much</strong> of a resource was used. It does <strong>not</strong> represent the cost.</p><p>Example</p><pre>┌──────────────────────┬──────────┐<br>│ Column               │ Value    │<br>├──────────────────────┼──────────┤<br>│ lineItem/UsageAmount │ 10       │<br>│ Unit                 │ Hrs      │<br>└──────────────────────┴──────────┘</pre><h4>lineItem/UnblendedRate</h4><p>The actual rate per unit charged for this line item before organization-level discounts.</p><p>Formula: <strong>UnblendedCost = UnblendedRate × UsageAmount</strong></p><p>Example</p><p>Suppose an EC2 instance costs <strong>$0.10/hour</strong>.</p><p>You use it for <strong>10 hours</strong>.</p><pre>┌─────────────┬────────────────┐<br>│ UsageAmount │ UnblendedRate  │<br>├─────────────┼────────────────┤<br>│ 10 hours    │ $0.10/hour     │<br>└─────────────┴────────────────┘</pre><p>Reserved Instance Example</p><p>Suppose an EC2 instance is fully covered by a Reserved Instance.</p><p>AWS documentation states:</p><p>For line items with LineItemType = DiscountedUsage, the UnblendedRate is 0.</p><pre>┌───────────────────┬──────────┬────────────────┬───────────────┐<br>│ LineItemType      │ Usage    │ UnblendedRate  │ UnblendedCost │<br>├───────────────────┼──────────┼────────────────┼───────────────┤<br>│ DiscountedUsage   │ 10 hours │ $0             │ $0            │<br>└───────────────────┴──────────┴────────────────┴───────────────┘</pre><p>This does <strong>not</strong> mean the instance was free.</p><p>The RI cost is represented separately by <strong>Fee</strong> or <strong>RIFee</strong> line items.</p><p>AWS sets the usage rate to zero because you’ve already paid (or committed to pay) for the Reserved Instance.</p><h4>lineItem/UnblendedCost</h4><p>The cost before discounts.</p><p>Formula: <strong>UnblendedCost = UnblendedRate × UsageAmount</strong></p><p>Example</p><pre>┌──────────┬───────────────┬───────────────┐<br>│ Usage    │ UnblendedRate │ UnblendedCost │<br>├──────────┼───────────────┼───────────────┤<br>│ 50 GB    │ $0.02         │ 50 × 0.02=$1  │<br>└──────────┴───────────────┴───────────────┘</pre><h4>lineItem/NetUnblendedRate</h4><p>The actual rate after discounts have been applied.</p><p>This column appears only if your account received discounts during the billing period.</p><p>Example</p><p>Normal EC2 rate: <strong>$0.10/hour</strong></p><p>Your company has a <strong>20% Enterprise Discount</strong>.</p><p>Actual rate becomes: <strong>$0.08/hour</strong></p><pre>┌────────────────┬───────────────────┐<br>│ UnblendedRate  │ NetUnblendedRate  │<br>├────────────────┼───────────────────┤<br>│ $0.10          │ $0.08             │<br>└────────────────┴───────────────────┘</pre><h4>lineItem/NetUnblendedCost</h4><p>The actual amount you pay after discounts on UnblendedCost.</p><p>Example</p><p>Suppose:</p><ul><li>Usage = <strong>100 hours</strong></li><li>Unblended rate = <strong>$0.10/hour</strong></li></ul><p>Unblended cost: <strong>100 × 0.10 = $10</strong></p><p>Your organization has a <strong>20% discount</strong>.</p><p>Net cost becomes: <strong>$8</strong></p><pre>┌─────────────┬───────────────┬──────────────────┐<br>│ UsageAmount │ UnblendedCost │ NetUnblendedCost │<br>├─────────────┼───────────────┼──────────────────┤<br>│ 100 hours   │ $10           │ $8               │<br>└─────────────┴───────────────┴──────────────────┘</pre><h4>lineItem/NormalizationFactor</h4><p>NormalizationFactor is a number assigned to each EC2 instance size.</p><p>It represents the relative size of an instance within the same instance family.</p><p>For example:</p><pre>┌───────────────┬──────────────────────┐<br>│ Instance Size │ Normalization Factor │<br>├───────────────┼──────────────────────┤<br>│ nano          │ 0.25                 │<br>│ micro         │ 0.5                  │<br>│ small         │ 1                    │<br>│ medium        │ 2                    │<br>│ large         │ 4                    │<br>│ xlarge        │ 8                    │<br>│ 2xlarge       │ 16                   │<br>│ 4xlarge       │ 32                   │<br>│ 8xlarge       │ 64                   │<br>└───────────────┴──────────────────────┘</pre><p>Notice the pattern.</p><p>Each larger instance is worth more normalized units.</p><p>AWS introduced normalization to support <strong>Reserved Instance (RI) size flexibility</strong>.</p><p>Before normalization, a Reserved Instance purchased for one instance size could only be applied to that exact instance size.</p><p>This was inflexible because customers often resize their instances as workloads change.</p><p>Example</p><p>You purchased: <strong>1 × m5.large Reserved Instance</strong></p><p>Later, you resize your workload to: <strong>4 × m5.small</strong></p><pre>┌─────────────────────────┬─────────────────────┬───────────────────────────────┬──────────────────────────┐<br>│     Instance Type       │Number of Instances  │ Normalized Units per Instance │ Total Normalized Units   │<br>├─────────────────────────┼─────────────────────┼───────────────────────────────┼──────────────────────────┤<br>│ Purchased RI: m5.large  │          1          │               4               │       1 × 4 = 4          │<br>│ Running: m5.small       │          4          │               1               │       4 × 1 = 4          │<br>└─────────────────────────┴─────────────────────┴───────────────────────────────┴──────────────────────────┘</pre><p>Since both have <strong>4 total normalized units</strong>, AWS can apply the <strong>m5.large Reserved Instance</strong> to all four <strong>m5.small</strong> instances.</p><p>Without normalization, AWS would simply compare:</p><p><strong>Purchased RI</strong>: m5.large<br><strong>Running</strong>: 4 × m5.small</p><p>Since the instance sizes are different, AWS would not know they represent the same compute capacity.</p><h4>lineItem/NormalizedUsageAmount</h4><p>This is simply your usage converted into normalized units.</p><p>Formula: <strong>NormalizedUsageAmount = UsageAmount × NormalizationFactor</strong></p><p>Example</p><p>Suppose you run m5.large for 10 hours.</p><p><strong>Normalization factor</strong>: large = 4</p><pre>┌───────────┬─────────────┬─────────────────────┬────────────────────────┐<br>│ Instance  │ UsageAmount │ NormalizationFactor │ NormalizedUsageAmount  │<br>├───────────┼─────────────┼─────────────────────┼────────────────────────┤<br>│ m5.large  │ 10 hours    │ 4                   │ 10* 4 = 40             │<br>└───────────┴─────────────┴─────────────────────┴────────────────────────┘</pre><h4><strong>lineItem/Operation</strong></h4><p>The specific AWS operation covered by this line item.</p><p>It represents the AWS operation or action that caused the usage.</p><p>What action/service operation produced the usage?</p><p>For example:</p><pre>RunInstances</pre><p>indicates the operation of launching an Amazon EC2 instance.</p><h4>lineItem/ProductCode</h4><p>The code of the product measured.</p><p>For example:</p><pre>AmazonEC2</pre><p>is the product code for Amazon Elastic Compute Cloud.</p><h4>lineItem/ResourceId</h4><p>It contains the unique identifier of the AWS resource that incurred the cost.</p><p>This column is optional and is included only if you enable Include Resource IDs when configuring your AWS Cost and Usage Report (CUR).</p><p>Think of it as answering the question:</p><p>“Which exact resource generated this charge?”</p><p>Without this column, you know you spent money on EC2 or S3, but you don’t know which EC2 instance or which S3 bucket was responsible.</p><p>Example</p><pre>┌─────────────┬──────────────────────┬──────┐<br>│ ProductCode │ ResourceId           │ Cost │<br>├─────────────┼──────────────────────┼──────┤<br>│ AmazonEC2   │ i-0123456789abcdef0  │ $35  │<br>│ AmazonEC2   │ i-0fedcba9876543210  │ $12  │<br>└─────────────┴──────────────────────┴──────┘</pre><p>ResourceId is not a universal unique ID across AWS</p><p>lineItem/ResourceId contains the resource identifier provided for that billing line, and its format depends on the AWS service.</p><p>For example, EC2 uses an instance ID eg i-0123456789abcdef</p><p>while S3 may use a bucket name eg my-bucket</p><p>So you should not assume that every ResourceId is globally unique across all AWS services.</p><p>For example, conceptually</p><pre>EC2:  abc123<br>S3:   abc123</pre><p>could potentially represent different resources because they belong to different services.</p><p>Two resources of the same AWS resource type generally cannot have the same resource identifier within the scope where that identifier is unique.</p><p>Some common AWS services and their resource identifiers are:</p><pre>┌─────────────────────────────────────────────┬──────────────────────────┐<br>│ AWS Service                                 │ Resource Identifier      │<br>├─────────────────────────────────────────────┼──────────────────────────┤<br>│ Amazon CloudFront                           │ Distribution ID          │<br>│ Amazon CloudSearch                          │ Search domain            │<br>│ Amazon DynamoDB                             │ DynamoDB table           │<br>│ Amazon Elastic Compute Cloud - Amazon EBS   │ Amazon EBS volume        │<br>│ Amazon Elastic Compute Cloud                │ Instance ID              │<br>│ Amazon Elastic Compute Cloud - CloudWatch   │ CloudWatch instance ID   │<br>│ Amazon EMR                                  │ MapReduce cluster        │<br>│ Amazon ElastiCache                          │ Cache cluster            │<br>│ Amazon OpenSearch Service                   │ Search domain            │<br>│ Amazon Glacier                              │ Vault                    │<br>│ Amazon Relational Database Service          │ Database                 │<br>│ Amazon Redshift                             │ Amazon Redshift cluster  │<br>│ Amazon Simple Storage Service               │ Amazon S3 bucket         │<br>│ Amazon Virtual Private Cloud                │ VPN ID                   │<br>│ AWS Lambda                                  │ Lambda function name     │<br>└─────────────────────────────────────────────┴──────────────────────────┘</pre><h4>lineItem/TaxType</h4><p>The type of tax that AWS applied to this line item.</p><p>Examples include:</p><ul><li>GST</li><li>VAT</li><li>US Sales Tax</li></ul><p>This field helps identify the type of tax charged separately from the actual AWS service usage cost.</p><h4>lineItem/UsageAccountId</h4><p>The account ID of the account that used this line item.</p><p>For organizations, this can be either the management account or a member account.</p><p>You can use this field to track costs or usage by account.</p><p>Example</p><p>Suppose an AWS Organization has multiple accounts:</p><pre>Organization<br><br>111111111111 (Management Account)<br>│<br>├── 222222222222 (Development)<br>├── 333333333333 (Production)<br>└── 444444444444 (Testing)</pre><p>The CUR may contain:</p><pre>┌─────────────────┬─────────────┬─────────┬──────┐<br>│ UsageAccountId  │ Service     │ Usage   │ Cost │<br>├─────────────────┼─────────────┼─────────┼──────┤<br>│ 222222222222    │ EC2         │ 100 hrs │ $50  │<br>│ 333333333333    │ S3          │ 200 GB  │ $20  │<br>│ 444444444444    │ Lambda      │ Requests│ $10  │<br>└─────────────────┴─────────────┴─────────┴──────┘</pre><p>The <strong>UsageAccountId</strong> tells you which account actually consumed the AWS resource.</p><h4>lineItem/UsageStartDate</h4><p>The start date and time when the resource usage began for that line item.</p><p>The time is stored in UTC.</p><p>The start time is <strong>inclusive</strong>.</p><p>The format is: <strong>YYYY-MM-DDTHH:mm:ssZ</strong></p><h4>lineItem/UsageEndDate</h4><p>The end date and time when the resource usage ended for that line item.</p><p>The time is stored in UTC.</p><p>The end time is <strong>exclusive</strong>.</p><p>The format is: YYYY-MM-DDTHH:mm:ssZ</p><p>It doesn’t specify that the resource usage has ended at that time it only specify that charge associated with the line item belongs to this duration that is lineItem/UsageStartDate and lineItem/UsageEndDate</p><h4>lineItem/UsageType</h4><p>The usage details of the line item.</p><p>It describes the type of resource usage being billed.</p><p>In simple terms: What was consumed?</p><p>Examples:</p><ul><li>EC2 instance hours</li><li>S3 storage</li><li>Data transfer</li><li>Lambda requests</li></ul><p>For example: <strong>USW2-BoxUsage:m2.2xlarge</strong></p><p>describes:</p><ul><li>Instance type: <strong>M2 High Memory Double Extra Large</strong></li><li>Region: <strong>US West (Oregon)</strong></li></ul><h3>Reservation Details</h3><p>Reservation columns contain information related to Reserved Instances. They describe how AWS allocates the upfront and recurring costs of a Reserved Instance to your usage during a billing period.</p><h4>Reservation columns</h4><ul><li>reservation/ReservationARN</li><li>reservation/SubscriptionId</li><li>reservation/AvailabilityZone</li><li>reservation/StartTime</li><li>reservation/EndTime</li><li>reservation/ModificationStatus</li><li>reservation/UpfrontValue</li><li>reservation/NetUpfrontValue</li><li>reservation/AmortizedUpfrontFeeForBillingPeriod</li><li>reservation/NetAmortizedUpfrontFeeForBillingPeriod</li><li>reservation/UnusedAmortizedUpfrontFeeForBillingPeriod</li><li>reservation/NetUnusedAmortizedUpfrontFeeForBillingPeriod</li><li>reservation/AmortizedUpfrontCostForUsage</li><li>reservation/NetAmortizedUpfrontCostForUsage</li><li>reservation/RecurringFeeForUsage</li><li>reservation/NetRecurringFeeForUsage</li><li>reservation/UnusedRecurringFee</li><li>reservation/NetUnusedRecurringFee</li><li>reservation/EffectiveCost</li><li>reservation/NetEffectiveCost</li><li>reservation/NumberOfReservations</li><li>reservation/UnitsPerReservation</li><li>reservation/TotalReservedUnits</li><li>reservation/UnusedQuantity</li><li>reservation/NormalizedUnitsPerReservation</li><li>reservation/TotalReservedNormalizedUnits</li><li>reservation/UnusedNormalizedUnitQuantity</li></ul><h4>reservation/ReservationARN</h4><p>Represents the Amazon Resource Name (ARN) of the Reserved Instance.</p><p>The ARN uniquely identifies the Reserved Instance in your AWS account.</p><p>Example</p><pre>┌──────────────────────────────┬──────────────────────────────────────────────────────────────────────┐<br>│ Column                       │ Value                                                                │<br>├──────────────────────────────┼──────────────────────────────────────────────────────────────────────┤<br>│ reservation/ReservationARN   │ arn:aws:ec2:us-east-1:123456789012:reserved-instances/abcd1234       │<br>└──────────────────────────────┴──────────────────────────────────────────────────────────────────────┘</pre><h4>reservation/SubscriptionId</h4><p>Represents the subscription identifier associated with the Reserved Instance purchase.</p><p>AWS uses this value internally to identify the Reserved Instance subscription.</p><ul><li><strong>reservation/SubscriptionId</strong> → identifies the <strong>RI subscription/offer</strong> associated with the billing line.</li><li><strong>reservation/ARN</strong> → identifies the <strong>specific Reserved Instance (RI)</strong> and is the <strong>preferred identifier</strong>.</li><li>Both can be used to associate CUR line items with an RI.</li><li><strong>ARN is more descriptive and reliable</strong> because it contains information such as service, region, account, and the specific RI identifier.</li></ul><p>Example</p><pre>┌──────────────────────────────┬─────────────┐<br>│ Column                       │ Value       │<br>├──────────────────────────────┼─────────────┤<br>│ reservation/SubscriptionId   │ 987654321   │<br>└──────────────────────────────┴─────────────┘</pre><h4>reservation/AvailabilityZone</h4><p>Represents the Availability Zone associated with the Reserved Instance.</p><p>This column is populated for <strong>zonal Reserved Instances</strong>.</p><p>Regional Reserved Instances may leave this field blank.</p><p>Example</p><pre>┌──────────────────────────────┬─────────────┐<br>│ Column                       │ Value       │<br>├──────────────────────────────┼─────────────┤<br>│ reservation/AvailabilityZone │ us-east-1a  │<br>└──────────────────────────────┴─────────────┘</pre><h4>reservation/StartTime</h4><p>Represents the date and time when the Reserved Instance lease begins.</p><p>Example</p><pre>┌────────────────────────┬──────────────────────┐<br>│ Column                 │ Value                │<br>├────────────────────────┼──────────────────────┤<br>│ reservation/StartTime  │ 2026-01-01T00:00:00Z │<br>└────────────────────────┴──────────────────────┘</pre><h4>reservation/EndTime</h4><p>Represents the date and time when the Reserved Instance lease expires.</p><p>Example</p><pre>┌──────────────────────┬──────────────────────┐<br>│ Column               │ Value                │<br>├──────────────────────┼──────────────────────┤<br>│ reservation/EndTime  │ 2027-01-01T00:00:00Z │<br>└──────────────────────┴──────────────────────┘</pre><h4>reservation/ModificationStatus</h4><p>Represents whether the Reserved Instance has been modified after it was purchased.</p><p>Example</p><p>Suppose you buy: m5.large 1-year Convertible RI</p><p>Initially reservation/ModificationStatus = Original</p><p>Later, you exchange it for another Convertible RI: m5.xlarge</p><p>Now the RI has been modified/exchanged, so its modification status can reflect that modification.</p><p>Possible values include</p><pre>┌──────────────────┬──────────────────────────────────────────────────────────────┐<br>│ Value            │ Meaning                                                      │<br>├──────────────────┼──────────────────────────────────────────────────────────────┤<br>│ Original         │ The Reserved Instance has never been modified.              │<br>│ System           │ Modified using the AWS Console or API.                      │<br>│ Manual           │ Modified with assistance from AWS Support.                  │<br>│ ManualWithData   │ Modified by AWS Support and includes calculated estimates.  │<br>└──────────────────┴──────────────────────────────────────────────────────────────┘</pre><h4>reservation/UpfrontValue</h4><p>Represents the total upfront payment made when purchasing a Reserved Instance.</p><p>This is the complete upfront amount paid and is <strong>not amortized</strong>.</p><p>Example</p><p>Suppose you purchase a 1-Year Partial Upfront Reserved Instance:</p><p>Total RI cost = $1000<br>Upfront payment = $600<br>Remaining recurring payment = $400</p><p>AWS records the upfront payment as:</p><pre>┌──────────────────────────────┬──────────────────────────────┐<br>│ lineItem/LineItemType        │ reservation/UpfrontValue     │<br>├──────────────────────────────┼──────────────────────────────┤<br>│ Fee                          │ $600                         │<br>└──────────────────────────────┴──────────────────────────────┘</pre><h4><strong>reservation/NetUpfrontValue</strong></h4><p>Represents the upfront value of the Reserved Instance after applicable discounts.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/AmortizedUpfrontFeeForBillingPeriod</h4><p>Represents the portion of the Reserved Instance’s upfront payment that is allocated to the current billing period.</p><p>It answers</p><p>How much of the RI’s upfront payment belongs to this billing month?</p><p>Hourly Amortized Upfront = Total Upfront Payment ÷ Total Hours in the RI Term<br>Amortized Upfront for Billing Period = Hourly Amortized Upfront × Hours in that Billing Period</p><p>Suppose you purchase a 1-Year All Upfront Reserved Instance:</p><ul><li>Total Upfront Payment: $1,200</li><li>RI Term: 1 year = 8,760 hours (365 days × 24 hrs, non-leap year)</li></ul><p>Hourly Amortized Upfront = $1,200 ÷ 8,760 hours = $0.136986/hour</p><p>Monthly billing periods</p><pre>┌───────────────────────────────┬──────────────────────────────────────────────────────────────┐<br>│      lineItem/LineItemType    │          reservation/AmortizedUpfrontFeeForBillingPeriod     │<br>├───────────────────────────────┼──────────────────────────────────────────────────────────────┤<br>│ RIFee (Jan - 31 days)         │              $0.136986 × 744 hours = $101.92                 │<br>│ RIFee (Feb - 28 days)         │              $0.136986 × 672 hours = $92.05                  │<br>│ RIFee (Apr - 30 days)         │              $0.136986 × 720 hours = $98.63                  │<br>└───────────────────────────────┴──────────────────────────────────────────────────────────────┘</pre><h4>reservation/NetAmortizedUpfrontFeeForBillingPeriod</h4><p>Represents the amortized upfront fee for the billing period after applicable discounts.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/UnusedAmortizedUpfrontFeeForBillingPeriod</h4><p>Represents the portion of the monthly amortized upfront fee that corresponds to Reserved Instance capacity that was not used during the billing period.</p><p>Formula: <strong>UnusedAmortizedUpfrontFeeForBillingPeriod = Monthly Amortized Upfront Fee × Unused Capacity %</strong></p><p>used capacity = Used Normalized Usage ÷ Reserved Normalized Units</p><p>unused capacity = Unused Normalized Usage ÷ Reserved Normalized Units</p><p>Example</p><p>Suppose</p><p><strong>Payment Option:</strong> All Upfront</p><p><strong>Reserved Instance:</strong> 2 × m5.large</p><p><strong>Normalization factor (m5.large):</strong> 4</p><p><strong>Reserved Capacity</strong> = 2 × m5.large = 8 normalized units</p><p><strong>RI purchase price:</strong> $7,200</p><p>Term: 1 year = 8,760 hours</p><p>Reserved CapacityDuring January, only 1.5 × m5.large ran on average</p><p>Used Capacity = 1.5 × 4 = 6 normalized units</p><p>Unused Capacity = 8 — 6 = 2 normalized units:</p><p>Hourly Amortized Upfront = $7,200 ÷ 8,760 hours = $0.8219/hour<br>Monthly Amortized Upfront (e.g., 744-hour January) = $0.8219 × 744 = $611.51</p><p>AmortizedUpfrontCostForUsage = $611.51 × (6/8) = $458.63<br>UnusedAmortizedUpfrontFeeForBillingPeriod = $611.51 × (2/8) = $152.88</p><p>Check: $458.63 + $152.88 = $611.51 (matches total amortized upfront for that month)</p><pre>┌────────────────────────────────┬───────────────────────┬────────────────────────────┬────────────────────────────────────────────┬──────────────────────────────────────────────────────┐<br>│    lineItem/LineItemType       │ product/instanceType  │ lineItem/UnblendedCost     │ reservation/AmortizedUpfrontCostForUsage   │reservation/UnusedAmortizedUpfrontFeeForBillingPeriod │<br>├────────────────────────────────┼───────────────────────┼────────────────────────────┼────────────────────────────────────────────┼──────────────────────────────────────────────────────┤<br>│             Usage              │       m5.large        │          $0.50             │                    null                    │                       null                           │<br>│       DiscountedUsage          │       m5.large        │           null             │                  $458.63                   │                       null                           │<br>│             RIFee              │         null          │           null             │                    null                    │                     $152.88                          │<br>└────────────────────────────────┴───────────────────────┴────────────────────────────┴────────────────────────────────────────────┴──────────────────────────────────────────────────────┘</pre><h4>reservation/NetUnusedAmortizedUpfrontFeeForBillingPeriod</h4><p>Represents the unused amortized upfront fee after applicable discounts.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/AmortizedUpfrontCostForUsage</h4><p>Represents the portion of the Reserved Instance’s <strong>amortized upfront payment</strong> that is allocated to a specific RI-covered usage line item.</p><p>It answers</p><p>Out of this month’s amortized upfront fee, how much belongs to this particular usage line?</p><p>AWS distributes the monthly amortized upfront fee across all usage covered by the Reserved Instance.</p><p>Formula:</p><p><strong>AmortizedUpfrontCostForUsage = AmortizedUpfrontFeeForBillingPeriod × (Normalized Usage for this Usage Line ÷ Total Normalized Usage Covered by the RI)</strong></p><p>Example same as above</p><blockquote>Note</blockquote><blockquote>For a given Reserved Instance (RI)</blockquote><blockquote>Sum of AmortizedUpfrontCostForUsage = AmortizedUpfrontFeeForBillingPeriod</blockquote><h4>reservation/NetAmortizedUpfrontCostForUsage</h4><p>Represents the amortized upfront cost allocated to a Reserved Instance usage line after applicable discounts.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/RecurringFeeForUsage</h4><p>Represents the portion of the monthly recurring Reserved Instance fee that is allocated to the Reserved Instance usage you actually consumed.</p><p>This column applies only to</p><ul><li>Partial Upfront Reserved Instances</li><li>No Upfront Reserved Instances</li></ul><p>It is always <strong>0</strong> for <strong>All Upfront Reserved Instances</strong> because the entire cost has already been paid upfront.</p><p>Formula:</p><p>RecurringFeeForUsage = RecurringFeeForBillingPeriod × (Used Normalized Usage ÷ Reserved Normalized Units)</p><p>UnusedRecurringFee = RecurringFeeForBillingPeriod × (Unused Normalized Usage ÷ Reserved Normalized Units)</p><p>Example</p><p><strong>Payment Option:</strong> Partial Upfront RI</p><p><strong>Reserved Instance:</strong> 2 × m5.large</p><p><strong>Normalization factor (m5.large):</strong> 4</p><p><strong>Reserved Capacity</strong> = 2 × m5.large = 8 normalized units</p><p><strong>Total recurring fee over the 1-year term</strong>: $3,000</p><p><strong>Hourly recurring rate</strong>: $3,000 ÷ 8,760 hours = $0.342466/hour</p><p><strong>RecurringFeeForBillingPeriod</strong> (January (744 hours))= $0.342466 × 744 = $254.79</p><p><strong>RecurringFeeForUsage</strong> = $254.79 × (6/8) = $191.09</p><p><strong>UnusedRecurringFee</strong> = $254.79 × (2/8) = $63.70</p><p>Check: $191.09 + $63.70 = $254.79 matches the full recurring fee for that billing period.</p><pre>┌───────────────────────────┬───────────────────────────┬──────────────────────────────────────────┬──────────────────────────────────┬────────────────────────────────────┐<br>│    lineItem/LineItemType  │    lineItem/ResourceId    │ reservation/RecurringFeeForBillingPeriod │ reservation/RecurringFeeForUsage │ reservation/UnusedRecurringFee     │<br>├───────────────────────────┼───────────────────────────┼──────────────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┤<br>│      DiscountedUsage      │       i-instanceA         │                 null                     │             $191.09              │                null                │<br>│           RIFee           │           null            │                $254.79                   │                null              │               $63.70               │<br>└───────────────────────────┴───────────────────────────┴──────────────────────────────────────────┴──────────────────────────────────┴────────────────────────────────────┘</pre><blockquote>Note</blockquote><blockquote>RecurringFeeForUsage + UnusedRecurringFee<br>= monthly recurring Reserved Instance fee.</blockquote><h4>reservation/NetRecurringFeeForUsage</h4><p>Represents the recurring Reserved Instance fee allocated to usage <strong>after applicable discounts</strong>.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/UnusedRecurringFee</h4><p>Represents the portion of the monthly recurring Reserved Instance fee that corresponds to unused RI capacity.</p><p>If your Reserved Instance is not fully utilized, this column shows the recurring fee associated with the unused capacity.</p><p>Example same as above</p><h4>reservation/EffectiveCost</h4><p>Represents the <strong>actual cost of an RI-covered usage line</strong>.</p><p>It includes:</p><ul><li>The amortized upfront cost allocated to the usage.</li><li>The recurring Reserved Instance fee allocated to the usage.</li></ul><p>Formula:</p><p><strong>EffectiveCost = AmortizedUpfrontCostForUsage + RecurringFeeForUsage</strong></p><p>From the last Examples:</p><ul><li>AmortizedUpfrontCostForUsage (Instance A, January) = $458.63</li><li>RecurringFeeForUsage (Instance A, January) = $191.09</li></ul><p>EffectiveCost = $458.63 + $191.09 = $649.72</p><p>That $649.72 is the true, all-in discounted cost for Instance A’s share of the RI that month — the number you’d compare against what Instance A would’ve cost at On-Demand rates, to see your actual savings.</p><pre>┌───────────────────────────┬───────────────────────────┬──────────────────────────────────────────┬─────────────────────────────────────┬───────────────────────────────┐<br>│ lineItem/LineItemType     │ lineItem/ResourceId       │ reservation/AmortizedUpfrontCostForUsage │ reservation/RecurringFeeForUsage    │ reservation/EffectiveCost     │<br>├───────────────────────────┼───────────────────────────┼──────────────────────────────────────────┼─────────────────────────────────────┼───────────────────────────────┤<br>│ DiscountedUsage           │ i-instanceA               │ $458.63                                  │ $191.09                             │ $649.72                       │<br>└───────────────────────────┴───────────────────────────┴──────────────────────────────────────────┴─────────────────────────────────────┴───────────────────────────────┘</pre><h4>reservation/NetEffectiveCost</h4><p>Represents the <strong>EffectiveCost after applicable discounts</strong>.</p><p>This column appears only if discounts apply during the billing period.</p><h4>reservation/NumberOfReservations</h4><p>Represents the number of Reserved Instances purchased.</p><p>one RI subscription might have several associated RI reservations.</p><p>The number of reservations covered by this subscription — one RI subscription might have several associated RI reservations.</p><p>Example</p><p>You purchase 5 identical Partial Upfront EC2 RIs (m5.large), 1-year term, billed monthly.</p><pre>┌──────────────────────────────┬─────────────────────────────────┐<br>│    lineItem/LineItemType     │reservation/NumberOfReservations │<br>├──────────────────────────────┼─────────────────────────────────┤<br>│            RIFee             │                5                │<br>└──────────────────────────────┴─────────────────────────────────┘</pre><h4>reservation/UnitsPerReservation</h4><p>Represents the usage capacity provided by a <strong>single Reserved Instance</strong> during the billing period.</p><p>Populates on both Fee and RIFee rows with <em>different</em> meanings.</p><p>On a Fee row: total units reserved for the entire subscription term (e.g. 744 hours/month × 12 months = 8,928).</p><p>On a RIFee row: total available units in just that billing period (e.g. 1 unit × 744 hours = 744).</p><pre>┌───────────────────────────────┬────────────────────────────────────┐<br>│ lineItem/LineItemType         │ reservation/UnitsPerReservation    │<br>├───────────────────────────────┼────────────────────────────────────┤<br>│ Fee                           │ 8928                               │<br>│ RIFee                         │ 744                                │<br>└───────────────────────────────┴────────────────────────────────────┘</pre><h4>reservation/TotalReservedUnits</h4><p>Represents the total Reserved Instance capacity available during the billing period.</p><p>Formula:</p><p><strong>TotalReservedUnits = NumberOfReservations × UnitsPerReservation</strong></p><ul><li><strong>NumberOfReservations</strong> → How many Reserved Instances are included in that reservation offering.</li><li><strong>UnitsPerReservation</strong> → The capacity of one Reserved Instance.</li></ul><p>RIFee row: total available units in the subscription for that period (5 × 744 = 3,720).</p><pre>┌───────────────────────────────┬──────────────────────────────┐<br>│ lineItem/LineItemType         │ reservation/TotalReservedUnits │<br>├───────────────────────────────┼──────────────────────────────┤<br>│ Fee                           │ 44640                        │<br>│ RIFee                         │ 3720                         │<br>└───────────────────────────────┴──────────────────────────────┘</pre><h4>reservation/UnusedQuantity</h4><p>Represents the Reserved Instance capacity that was purchased but not used.</p><p>Formula:</p><p><strong>UnusedQuantity = TotalReservedUnits − Actual Usage</strong></p><p>Say your workload only used 3,530 of the available 3,720 hours this month.</p><pre>┌───────────────────────────────┬──────────────────────────────┐<br>│ lineItem/LineItemType         │ reservation/UnusedQuantity  │<br>├───────────────────────────────┼──────────────────────────────┤<br>│ RIFee                         │ 190                          │<br>└───────────────────────────────┴──────────────────────────────┘</pre><h4>reservation/NormalizedUnitsPerReservation</h4><p>Represents the normalized capacity provided by one Reserved Instance.</p><p>The number of normalized units for each instance of a reservation subscription. (Applies mainly to size-flexible Regional RIs — AWS’s own service list for this column is Amazon RDS.)</p><p>Normalization is based on the EC2 instance size.</p><p>Formula:</p><p><strong>NormalizedUnitsPerReservation = UnitsPerReservation × NormalizationFactor</strong></p><h4>reservation/TotalReservedNormalizedUnits</h4><p>The total number of reserved normalized units for all instances for a reservation subscription.</p><p>Formula:</p><p><strong>TotalReservedNormalizedUnits = NormalizedUnitsPerReservation × NumberOfReservations</strong></p><h4>reservation/UnusedNormalizedUnitQuantity</h4><p>Represents the normalized Reserved Instance capacity that was purchased but not used.</p><p>The number of unused normalized units for a size-flexible Regional RI that you didn’t use during this billing period.</p><p>Formula:<br><strong>UnusedNormalizedUnitQuantity =<br>UnusedQuantity × NormalizationFactor</strong></p><h3>Pricing details</h3><h3>Pricing details</h3><p>Pricing columns in AWS CUR show the raw price information used to calculate a line item cost.</p><p>Pricing columns do NOT include</p><ul><li>Spot Instances pricing</li><li>AWS Marketplace products</li><li>Upfront RI fees (one-time payments)</li><li>Monthly RI recurring fees</li></ul><p>So pricing columns mainly represent on-demand style reference pricing and rate metadata.</p><h4>pricing columns</h4><ul><li>pricing/LeaseContractLength</li><li>pricing/OfferingClass</li><li>pricing/publicOnDemandCost</li><li>pricing/publicOnDemandRate</li><li>pricing/purchaseOption</li><li>pricing/RateCode</li><li>pricing/RateId</li><li>pricing/term</li><li>pricing/unit</li></ul><h4>pricing/LeaseContractLength</h4><p>Represents the duration of a Reserved Instance contract.</p><p>Possible values 1yr 3yr</p><h4>pricing/OfferingClass</h4><p>Represents the type of Reserved Instance flexibility. possible values — Standard, Convertible</p><h4>pricing/publicOnDemandCost</h4><p>Represents the total cost if the usage was charged at On-Demand rates. Formulae</p><pre>publicOnDemandCost = usage × publicOnDemandRate</pre><p>Example</p><pre>┌────────────────┬────────────┐<br>│ Item           │ Value      │<br>├────────────────┼────────────┤<br>│ Usage          │ 100 hours  │<br>│ On-Demand Rate │ $0.10/hour │<br>└────────────────┴────────────┘</pre><p>In CUR</p><pre>┌────────────────────────────┬───────┐<br>│ Column                     │ Value │<br>├────────────────────────────┼───────┤<br>│ pricing/publicOnDemandCost │ $10   │<br>└────────────────────────────┴───────┘</pre><blockquote><strong>pricing/publicOnDemandCost</strong></blockquote><blockquote>cost at AWS public On-Demand rates, ignoring discounts, Savings Plans, or Reserved Instances.</blockquote><blockquote>whereas</blockquote><blockquote><strong>lineItem/UnblendedCost</strong></blockquote><blockquote>actual cost charged for the line item after AWS applies pricing such as RI, Savings Plans, private pricing, or discounts.</blockquote><h4>pricing/publicOnDemandRate</h4><p>Represents the standard AWS on-demand price per unit of usage.</p><p>Example</p><pre>┌───────────────┬────────────┐<br>│ Instance Type │ Rate       │<br>├───────────────┼────────────┤<br>│ m5.large      │ $0.10/hour │<br>└───────────────┴────────────┘</pre><p>In CUR</p><pre>┌────────────────────────────┬───────┐<br>│ Column                     │ Value │<br>├────────────────────────────┼───────┤<br>│ pricing/publicOnDemandRate │ $0.10 │<br>└────────────────────────────┴───────┘</pre><h4>pricing/PurchaseOption</h4><p>Represents how you paid for the usage or reservation.</p><p>possible values are All Upfront, Partial Upfront, No Upfront</p><h4>pricing/RateCode</h4><p>identifies a specific price tier in the AWS Price List.</p><p>RateCode is designed to <strong>uniquely</strong> identify a specific rate/price dimension in the pricing data, and is typically constructed using the product SKU + RateId.</p><h4>pricing/RateId</h4><p>Represents an identifier for a specific rate entry. It is not necessarily globally unique.</p><p>RateId tells you which rate/price dimension has been applied within a single AWS pricing product (SKU). A single SKU can have multiple rates when the product has tiered pricing, such as S3.</p><p>Example</p><p>Suppose one S3 pricing product/SKU represents:</p><pre>Product     = Amazon S3<br>Region      = US East (N. Virginia)<br>Usage Type  = TimedStorage-ByteHrs<br>Unit        = GB-Mo<br>SKU         = S3-ABC123</pre><p>That <strong>one SKU</strong> can have multiple pricing dimensions because S3 has tiered pricing:</p><pre>┌──────────────────────┬──────────┬────────────┬──────────────┐<br>│ Usage Range          │ RateId   │ Price      │ RateCode     │<br>├──────────────────────┼──────────┼────────────┼──────────────┤<br>│ First 50 TB/month    │ RATE001  │ $0.023/GB  │ S3-ABC123.001│<br>│ Next 450 TB/month    │ RATE002  │ $0.022/GB  │ S3-ABC123.002│<br>│ Above 500 TB/month   │ RATE003  │ $0.021/GB  │ S3-ABC123.003│<br>└──────────────────────┴──────────┴────────────┴──────────────┘</pre><p>RateId → tells you which rate within the SKU.</p><p>RateCode → identifies the specific rate/price dimension, typically using the SKU + RateId.</p><h4>pricing/term</h4><p>Represents whether usage is under On-Demand or Reserved etc</p><p>Typical values are:</p><pre>┌──────────────────────┬──────────────────────────────────────────────────────┐<br>│  pricing/Term value  │                         Meaning                      │<br>├──────────────────────┼──────────────────────────────────────────────────────┤<br>│      OnDemand        │ Pay-as-you-go pricing (no commitment)                │<br>│      Reserved        │ Reserved Instance pricing                            │<br>│        Spot          │ Spot Instance pricing (for services that support it) │<br>│     SavingsPlan      │ Savings Plans pricing                                │<br>│      FreeTier        │ Free tier pricing (where applicable)                 │<br>└──────────────────────┴──────────────────────────────────────────────────────┘</pre><h4>pricing/unit</h4><p>Represents the unit used for billing calculation.</p><p>Example</p><pre>┌─────────┬───────────────────────┐<br>│ Service │ Unit                  │<br>├─────────┼───────────────────────┤<br>│ EC2     │ Hours                 │<br>│ S3      │ GB-month              │<br>│ Lambda  │ Requests / GB-seconds │<br>└─────────┴───────────────────────┘</pre><h3>Product details</h3><p>The product columns provide metadata about the product that incurred the expense, and the line item. The product columns are dynamic, and their visibility in Cost and Usage Reports depends on the usage of product in the billing period</p><h4>product columns</h4><ul><li>product/instance</li><li>product/instanceFamily</li><li>product/instanceSize</li><li>product/instanceType</li><li>product/instanceTypeFamily</li><li>product/operatingSystem</li><li>product/operation</li><li>product/ProductName</li><li>product/region</li><li>product/regioncode</li><li>product/servicecode</li><li>product/servicename</li><li>product/sku</li></ul><h4>product/instance</h4><p>Represents the exact EC2 instance model used in the service.</p><p>Example</p><pre>┌──────────────────┬──────────┐<br>│ Column           │ Value    │<br>├──────────────────┼──────────┤<br>│ product/instance │ m5.large │<br>└──────────────────┴──────────┘</pre><h4>product/instanceFamily</h4><p>Represents the family group of the instance.</p><p>Example</p><pre>┌───────────────┬─────────────────┐<br>│ Instance Type │ Instance Family │<br>├───────────────┼─────────────────┤<br>│ m5.large      │ m5              │<br>│ c5.xlarge     │ c5              │<br>└───────────────┴─────────────────┘</pre><h4>product/instanceSize</h4><p>Represents the size within the instance family.</p><p>Example</p><pre>┌────────────┬────────┐<br>│ Instance   │ Size   │<br>├────────────┼────────┤<br>│ m5.large   │ large  │<br>│ m5.xlarge  │ xlarge │<br>└────────────┴────────┘</pre><h4>product/instanceType</h4><p>Represents the full EC2 instance type (family + size).</p><p>Example</p><pre>┌──────────────────────┬──────────┐<br>│ Column               │ Value    │<br>├──────────────────────┼──────────┤<br>│ product/instanceType │ m5.large │<br>└──────────────────────┴──────────┘</pre><h4>product/instanceTypeFamily</h4><p>Represents the broader classification of instance type generation and category.</p><p>Example</p><pre>┌───────────────┬─────────────────┐<br>│ Instance Type │ Instance Family │<br>├───────────────┼─────────────────┤<br>│ m5.large      │ m5              │<br>│ c5.xlarge     │ c5              │<br>└───────────────┴─────────────────┘</pre><h4>product/operatingSystem</h4><p>Represents the OS used on the instance.</p><p>Example</p><pre>┌─────────────────────────┬───────┐<br>│ Column                  │ Value │<br>├─────────────────────────┼───────┤<br>│ product/operatingSystem │ Linux │<br>└─────────────────────────┴───────┘</pre><h4>product/operation</h4><p>Represents the type of action performed in AWS service.</p><p>Example</p><pre>┌─────────┬──────────────┐<br>│ Service │ Operation    │<br>├─────────┼──────────────┤<br>│ EC2     │ RunInstances │<br>│ S3      │ PutObject    │<br>└─────────┴──────────────┘</pre><h4>product/ProductName</h4><p>Represents the human-readable AWS service name.</p><p>Example</p><pre>┌─────────────────────┬────────────────────────────────┐<br>│ Column              │ Value                          │<br>├─────────────────────┼────────────────────────────────┤<br>│ product/ProductName │ Amazon Elastic Compute Cloud   │<br>└─────────────────────┴────────────────────────────────┘</pre><h4>product/region</h4><p>Represents the AWS region name (human readable).</p><p>Example</p><pre>┌────────────────┬───────────────────────┐<br>│ Column         │ Value                 │<br>├────────────────┼───────────────────────┤<br>│ product/region │ US East (N. Virginia) │<br>└────────────────┴───────────────────────┘</pre><h4>product/regioncode</h4><p>Represents the short region identifier used in AWS systems.</p><p>Example</p><pre>┌───────────────────────┬─────────────┐<br>│ Region                │ Region Code │<br>├───────────────────────┼─────────────┤<br>│ US East (N. Virginia) │ us-east-1   │<br>│ Mumbai                │ ap-south-1  │<br>└───────────────────────┴─────────────┘</pre><h4>product/servicecode</h4><p>Represents the internal AWS service identifier.</p><p>Example</p><pre>┌─────────┬──────────────┐<br>│ Service │ Service Code │<br>├─────────┼──────────────┤<br>│ EC2     │ AmazonEC2    │<br>│ S3      │ AmazonS3     │<br>└─────────┴──────────────┘</pre><h4>product/servicename</h4><p>Represents the full official service name.</p><p>Example</p><pre>┌─────────────────────┬────────────────────────────────┐<br>│ Column              │ Value                          │<br>├─────────────────────┼────────────────────────────────┤<br>│ product/servicename │ Amazon Elastic Compute Cloud   │<br>└─────────────────────┴────────────────────────────────┘</pre><h4>product/sku</h4><p>Represents the unique AWS pricing identifier for a product configuration.</p><p>Example</p><pre>┌─────────────┬──────────────┐<br>│ Column      │ Value        │<br>├─────────────┼──────────────┤<br>│ product/sku │ ABC123XYZ789 │<br>└─────────────┴──────────────┘</pre><p><strong>SKU (Stock Keeping Unit)</strong></p><p>A SKU is a unique ID assigned by AWS to a specific product configuration. A product is defined by attributes such as Service (EC2, S3, etc.), Instance type, Instance family, Operating system, Region, Tenancy Every unique combination of these attributes gets its own SKU. AWS uses the SKU to look up the product’s price in its Pricing Catalog (using the Price List API).</p><p>Then the cost is calculated as lineItem/UnblendedCost = lineItem/UsageAmount × SKU Price</p><p>Example</p><pre>┌────────┬─────────────────────────────────────────┬─────────────┐<br>│ SKU    │ Product Configuration                   │ Price       │<br>├────────┼─────────────────────────────────────────┼─────────────┤<br>│ SKU001 │ EC2, t3.medium, Linux, Mumbai           │ $0.052/hour │<br>│ SKU002 │ EC2, t3.medium, Windows, Mumbai         │ $0.110/hour │<br>│ SKU003 │ EC2, m5.large, Linux, Mumbai            │ $0.096/hour │<br>└────────┴─────────────────────────────────────────┴─────────────┘</pre><blockquote>AWS assigns a SKU so each product configuration can be identified using a single ID. Without a SKU, AWS would have to match multiple attributes (such as instance type, operating system, region, and tenancy) every time it needed to identify a product or look up its price.</blockquote><h3>Resource tags details</h3><p>Resource tag columns contain <strong>user-defined cost allocation tags</strong> that you create and assign to AWS resources. These tags help you organize, track, and analyze AWS costs based on your own business requirements.</p><p>For example, you can tag resources by:</p><ul><li>Owner</li><li>Project</li><li>Environment</li><li>Department</li><li>Application</li><li>Purpose</li></ul><p>Once a cost allocation tag is activated in AWS Billing, it appears as a separate column in the Cost and Usage Report (CUR).</p><p>For example, if you create a tag named <strong>Owner</strong>, the CUR contains the column:</p><pre>resourceTags/user:Owner</pre><p>Similarly, a tag named <strong>Environment</strong> appears as:</p><pre>resourceTags/user:Environment</pre><p>Example</p><p>Suppose you have the following AWS resources.</p><pre>┌──────────────────┬─────────┬──────┬───────┬─────────────┐<br>│ Resource         │ Service │ Cost │ Owner │ Environment │<br>├──────────────────┼─────────┼──────┼───────┼─────────────┤<br>│ i-1234567890     │ EC2     │ $50  │ Alice │ Production  │<br>│ i-9876543210     │ EC2     │ $25  │ Bob   │ Development │<br>│ company-backups  │ S3      │ $15  │ Alice │ Production  │<br>└──────────────────┴─────────┴──────┴───────┴─────────────┘</pre><p>The corresponding CUR contains</p><pre>┌──────────────────┬────────────┬──────┬─────────────────────────┬───────────────────────────────┐<br>│ ResourceId       │ Service    │ Cost │ resourceTags/user:Owner │ resourceTags/user:Environment │<br>├──────────────────┼────────────┼──────┼─────────────────────────┼───────────────────────────────┤<br>│ i-1234567890     │ Amazon EC2 │ $50  │ Alice                   │ Production                    │<br>│ i-9876543210     │ Amazon EC2 │ $25  │ Bob                     │ Development                   │<br>│ company-backups  │ Amazon S3  │ $15  │ Alice                   │ Production                    │<br>└──────────────────┴────────────┴──────┴─────────────────────────┴───────────────────────────────┘</pre><h4>Common Resource Tag Columns</h4><ul><li>resourceTags/user:creator</li><li>resourceTags/user:name</li><li>resourceTags/user:owner</li><li>resourceTags/user:purpose</li></ul><blockquote>Note</blockquote><blockquote>Resource tag columns appear in the Cost and Usage Report only for activated cost allocation tags. If a tag has not been activated in AWS Billing or a resource does not have that tag assigned, the corresponding value in the CUR is blank.</blockquote><h4>resourceTags/user:creator</h4><p>Represents the user who created the AWS resource.</p><p>This tag is commonly used to identify who provisioned a resource.</p><p>Example</p><pre>┌──────────────┬───────────────────────────┐<br>│ Resource     │ resourceTags/user:creator │<br>├──────────────┼───────────────────────────┤<br>│ EC2 Instance │ Alice                     │<br>│ S3 Bucket    │ Bob                       │<br>└──────────────┴───────────────────────────┘</pre><h4>resourceTags/user:name</h4><p>Represents a user-defined name associated with the resource.</p><p>This tag helps identify resources more easily than using resource IDs.</p><p>Example</p><pre>┌──────────────┬────────────────────────┐<br>│ Resource     │ resourceTags/user:name │<br>├──────────────┼────────────────────────┤<br>│ EC2 Instance │ Web Server             │<br>│ RDS Instance │ Customer Database      │<br>└──────────────┴────────────────────────┘</pre><h4>resourceTags/user:owner</h4><p>Represents the owner responsible for the resource.</p><p>This tag is commonly used for cost allocation and accountability.</p><p>Example</p><pre>┌─────────────────┬────────────────────────┐<br>│ Resource        │ resourceTags/user:owner│<br>├─────────────────┼────────────────────────┤<br>│ EC2 Instance    │ Team A                 │<br>│ Lambda Function │ Team B                 │<br>│ S3 Bucket       │ Finance Team           │<br>└─────────────────┴────────────────────────┘</pre><h4>resourceTags/user:purpose</h4><p>Represents the reason or purpose for creating the resource.</p><p>This helps distinguish resources created for different business needs.</p><h4>Example</h4><pre>┌─────────────────┬──────────────────────────┐<br>│ Resource        │ resourceTags/user:purpose│<br>├─────────────────┼──────────────────────────┤<br>│ EC2 Instance    │ Production Application   │<br>│ Lambda Function │ Daily Backup             │<br>│ S3 Bucket       │ Log Storage              │<br>└─────────────────┴──────────────────────────┘</pre><h3><strong>Savings Plans details</strong></h3><p>Savings Plan columns contain information about your Savings Plan purchase, commitment, and how AWS allocates the Savings Plan cost to covered usage.</p><p>A Savings Plan is a pricing model where you commit to spending a fixed amount (for example, <strong>$10/hour</strong>) for either <strong>1 year</strong> or <strong>3 years</strong> in exchange for discounted pricing on eligible AWS services.</p><h4>Savings Plan Columns</h4><ul><li>savingsPlan/SavingsPlanArn</li><li>savingsPlan/StartTime</li><li>savingsPlan/EndTime</li><li>savingsPlan/InstanceTypeFamily</li><li>savingsPlan/OfferingType</li><li>savingsPlan/PaymentOption</li><li>savingsPlan/PurchaseTerm</li><li>savingsPlan/Region</li><li>savingsPlan/AmortizedUpfrontCommitmentForBillingPeriod</li><li>savingsPlan/NetAmortizedUpfrontCommitmentForBillingPeriod</li><li>savingsPlan/RecurringCommitmentForBillingPeriod</li><li>savingsPlan/NetRecurringCommitmentForBillingPeriod</li><li>savingsPlan/NetSavingsPlanEffectiveCost</li><li>savingsPlan/SavingsPlanEffectiveCost</li><li>savingsPlan/SavingsPlanRate</li><li>savingsPlan/UsedCommitment</li><li>savingsPlan/TotalCommitmentToDate</li></ul><h4>savingsPlan/SavingsPlanArn</h4><p>The unique Amazon Resource Name (ARN) that identifies the Savings Plan.</p><p>format:</p><pre>arn:aws:savingsplans::&lt;AWS_ACCOUNT_ID&gt;:savingsplan/&lt;SAVINGS_PLAN_ID&gt;<br>or<br>arn:aws:savingsplans::&lt;account_id&gt;:savingsplan/&lt;uuid&gt;</pre><ul><li>: The standard global partition prefix.</li><li><strong>savingsplans</strong>: The dedicated AWS service namespace.</li><li><strong>::</strong>: The region field is intentionally left blank because Savings Plans are managed as a <strong>global resource</strong> at the account level.</li><li><strong>&lt;account-id&gt;</strong>: Your specific 12-digit AWS account number, which ensures no other AWS customer can duplicate the string.</li><li><strong>savingsplan/&lt;uuid&gt;</strong>: A universally unique identifier (UUID) randomly generated by AWS at the moment of purchase.</li></ul><p>Example</p><pre>┌────────────────┬────────────────────────────────────────────────────────────────────┐<br>│ Column         │ Value                                                              │<br>├────────────────┼────────────────────────────────────────────────────────────────────┤<br>│ SavingsPlanArn │ arn:aws:savingsplans::123456789012:savingsplan/sp-0123456789abcdef │<br>└────────────────┴────────────────────────────────────────────────────────────────────┘</pre><h4>savingsPlan/StartTime</h4><p>The date and time when the Savings Plan starts.</p><p>Example</p><pre>┌───────────┬───────────────────────┐<br>│ Column    │ Value                 │<br>├───────────┼───────────────────────┤<br>│ StartTime │ 2026-01-01T00:00:00Z  │<br>└───────────┴───────────────────────┘</pre><h4>savingsPlan/EndTime</h4><p>The date and time when the Savings Plan expires.</p><p>Example</p><pre>┌─────────┬──────────────────────┐<br>│ Column  │ Value                │<br>├─────────┼──────────────────────┤<br>│ EndTime │ 2027-01-01T00:00:00Z │<br>└─────────┴──────────────────────┘</pre><h4>savingsPlan/InstanceTypeFamily</h4><p>Specifies the EC2 instance family associated with the Savings Plan.</p><p>Example</p><pre>┌───────────────┬──────────────────────┐<br>│ EC2 Instance  │ Instance Type Family │<br>├───────────────┼──────────────────────┤<br>│ m5.large      │ m5                   │<br>│ m5.xlarge     │ m5                   │<br>│ c5.large      │ c5                   │<br>└───────────────┴──────────────────────┘</pre><blockquote><strong>Note</strong></blockquote><blockquote>This column is mainly used for EC2 Instance Savings Plans. For Compute Savings Plans, it may be blank because Compute Savings Plans are flexible across instance families.</blockquote><h4>savingsPlan/OfferingType</h4><p>Specifies the type of Savings Plan purchased.</p><p>Possible values include:</p><ul><li>Compute Savings Plan</li><li>EC2 Instance Savings Plan</li><li>SageMaker Savings Plan</li><li>Database Savings Plan</li></ul><h4>savingsPlan/PaymentOption</h4><p>Specifies how the Savings Plan was purchased.</p><p>Possible values:</p><ul><li>All Upfront</li><li>Partial Upfront</li><li>No Upfront</li></ul><h4>savingsPlan/PurchaseTerm</h4><p>Specifies the duration of the Savings Plan.</p><p>Possible values:</p><ul><li>1 Year</li><li>3 Years</li></ul><h4>savingsPlan/Region</h4><p>The AWS Region associated with the Savings Plan.</p><blockquote><strong>Note</strong></blockquote><blockquote>Compute Savings Plans are flexible across AWS Regions for eligible services, whereas EC2 Instance Savings Plans are scoped to a Region.</blockquote><h4>savingsPlan/AmortizedUpfrontCommitmentForBillingPeriod</h4><p>This column represents the portion of the Savings Plan upfront payment that belongs to the current billing period.</p><p>It answers:</p><p><em>How much of the upfront payment belongs to this billing month?</em></p><p>Formula</p><p><strong>Hourly Amortized Upfront = Total Upfront Payment ÷ Total Hours in the SP Term<br>Amortized Upfront for Billing Period = Hourly Amortized Upfront × Hours in that Billing Period</strong></p><p>Example</p><p>Suppose you purchase a <strong>1-Year Partial Upfront Savings Plan</strong>.</p><p><strong>Total Upfront Payment</strong>: $1,200</p><p><strong>Savings Plan Term</strong>: 1 year = 8,760 hours (365 days × 24 hrs, non-leap year)</p><p>Hourly Amortized Upfront = $1,200 ÷ 8,760 hours = $0.136986/hour</p><p>Monthly billing periods</p><pre>┌─────────────────────────────────────────┬──────────────────────────────────────────────────────────────┐<br>│            lineItem/LineItemType        │      savingsPlan/AmortizedUpfrontCommitmentForBillingPeriod  │<br>├─────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤<br>│ SavingsPlanRecurringFee (Jan - 31 days) │              $0.136986 × 744 hours = $101.92                 │<br>│ SavingsPlanRecurringFee (Feb - 28 days) │              $0.136986 × 672 hours = $92.05                  │<br>│ SavingsPlanRecurringFee (Apr - 30 days) │              $0.136986 × 720 hours = $98.63                  │<br>└─────────────────────────────────────────┴──────────────────────────────────────────────────────────────┘</pre><h4><strong>savingsPlan/NetAmortizedUpfrontCommitmentForBillingPeriod</strong></h4><p>This column represents the amortized upfront commitment after any applicable discounts.</p><p>This column appears only if your account receives discounts during the billing period.</p><h4>savingsPlan/RecurringCommitmentForBillingPeriod</h4><p>This column represents the recurring commitment charged during the billing period.</p><p>It applies to:</p><ul><li>Partial Upfront Savings Plans</li><li>No Upfront Savings Plans</li></ul><p>For <strong>All Upfront Savings Plans</strong>, this value is <strong>0</strong> because the entire commitment is paid upfront.</p><p>Example</p><ul><li>Total commitment: <strong>$0.50/hour</strong></li><li>Term: 1 year = 8,760 hours</li><li>Total contract value over the term: $0.50 × 8,760 = <strong>$4,380</strong></li><li>Partial Upfront payment: <strong>$1,200</strong> (from the above example) → amortized to $0.136986/hour</li><li>Remaining recurring commitment: $4,380 − $1,200 = <strong>$3,180</strong>, spread over 8,760 hours:</li></ul><p>Recurring Hourly Rate = $3,180 ÷ 8,760 hours = $0.363014/hour</p><p>Monthly billing periods</p><pre>┌─────────────────────────────────────────────┬──────────────────────────────────────────────────────────────┐<br>│             lineItem/LineItemType           │       savingsPlan/RecurringCommitmentForBillingPeriod        │<br>├─────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤<br>│ SavingsPlanRecurringFee (Jan - 744 hrs)     │              $0.363014 × 744 hours = $270.12                 │<br>│ SavingsPlanRecurringFee (Feb - 672 hrs)     │              $0.363014 × 672 hours = $244.02                 │<br>│ SavingsPlanRecurringFee (Apr - 720 hrs)     │              $0.363014 × 720 hours = $261.37                 │<br>└─────────────────────────────────────────────┴──────────────────────────────────────────────────────────────┘</pre><h4>savingsPlan/NetRecurringCommitmentForBillingPeriod</h4><p>This column represents the recurring commitment after discounts have been applied.</p><p>This column appears only when your account receives discounts.</p><h4>savingsPlan/SavingsPlanRate</h4><p>The Savings Plan Rate is the discounted per-unit price applied to eligible usage under a Savings Plan.</p><p>Example</p><p>Suppose an <strong>EC2 instance runs for 2 hours</strong> and is covered by a Savings Plan.</p><ul><li><strong>On-Demand rate:</strong> $0.10/hour</li><li><strong>Savings Plan discounted rate:</strong> $0.06/hour</li></ul><pre>┌───────────────────────────┬────────────────────────────┬──────────────────────────────┬───────────────────────────────────────┐<br>│ lineItem/LineItemType     │ lineItem/UnblendedCost     │ savingsPlan/SavingsPlanRate  │ savingsPlan/SavingsPlanEffectiveCost  │<br>├───────────────────────────┼────────────────────────────┼──────────────────────────────┼───────────────────────────────────────┤<br>│ Usage                     │ $0.20                      │ NULL                         │ NULL                                  │<br>│ SavingsPlanNegation       │ -$0.20                     │ NULL                         │ NULL                                  │<br>│ SavingsPlanCoveredUsage   │ $0.20                      │ $0.06/hour                   │ $0.12                                 │<br>└───────────────────────────┴────────────────────────────┴──────────────────────────────┴───────────────────────────────────────┘</pre><h4>savingsPlan/SavingsPlanEffectiveCost</h4><p>SavingsPlanEffectiveCost is simply the actual dollar amount you pay for a specific piece of Savings-Plan-covered usage — calculated as the discounted Savings Plan rate multiplied by how much you used. It&#39;s the real, out-of-pocket cost for that line item, as opposed to the on-demand-equivalent number shown elsewhere on the same row.</p><p>SavingsPlanEffectiveCost = SavingsPlanRate × UsageAmount</p><p><strong>AWS’s official definition:</strong></p><blockquote><strong><em>savingsPlan/SavingsPlanEffectiveCost</em></strong><em><br> Description: The proportion of the Savings Plans monthly commitment amount (upfront and recurring) that is allocated to each usage line.</em></blockquote><p><strong>Why AWS phrases it that way instead of just saying “rate × usage”:</strong></p><p>AWS is describing the number from the <em>funding-source</em> perspective rather than the <em>arithmetic</em> perspective:</p><ul><li>Your Savings Plan already has a fixed monthly pool of money behind it — AmortizedUpfrontCommitmentForBillingPeriod + RecurringCommitmentForBillingPeriod. That pool exists whether or not you use any resources.</li><li>Every hour of usage that gets the SP discount is, in effect, “spending down” a piece of that pool.</li><li>So instead of framing it as a pricing calculation (“here’s the discounted rate times your usage”), AWS frames it as an <em>allocation</em> problem: “of the fixed monthly commitment you already paid for, here’s the specific portion this particular usage line consumed.”</li></ul><h4>savingsPlan/NetSavingsPlanEffectiveCost</h4><p>This is the final cost after applying credits, refunds, or billing adjustments.</p><p>This column is included in your report only when your account has a discount in the applicable billing period.</p><h4>savingsPlan/UsedCommitment</h4><p>This column shows how much of your Savings Plan commitment is actually consumed by usage in a billing period.</p><p>It represents the portion of your committed spend that was used to cover eligible usage.</p><p>Suppose:</p><ul><li>EC2 On-Demand rate = <strong>$0.10/hour</strong></li><li>Savings Plan rate = <strong>$0.06/hour</strong></li><li>Savings Plan commitment = <strong>$0.10/hour</strong></li><li>EC2 runs for <strong>1 hour</strong></li></ul><p>On-Demand cost = $0.10 × 1 hour = $0.10</p><p>SP cost = $0.06 × 1 hour = $0.06</p><p>The customer has a Savings Plan commitment of $0.10/hour.</p><p>But the EC2 usage only consumes $0.06 of that commitment.</p><p>So:</p><p>UsedCommitment = $0.06</p><p>$0.04 dollar gets wasted as you still have to pay for it even if you hadn’t used it</p><pre>┌────────────────────────────┬──────────────────────────────────┬──────────────────────────────┐<br>│    lineItem/LineItemType   │savingsPlan/TotalCommitmentToDate │ savingsPlan/UsedCommitment   │<br>├────────────────────────────┼──────────────────────────────────┼──────────────────────────────┤<br>│  SavingsPlanRecurringFee   │              $0.10               │            $0.06             │<br>└────────────────────────────┴──────────────────────────────────┴──────────────────────────────┘</pre><h4>savingsPlan/TotalCommitmentToDate</h4><p>The total amortized upfront commitment and recurring commitment to date, for that hour.</p><p>Despite the words “to date,” it does <strong>not</strong> accumulate across hours. It’s a fixed value recalculated identically every hour — your $/hour commitment amount</p><p>TotalCommitmentToDate (for a given hour) <br> = AmortizedUpfrontCommitmentForBillingPeriod (for that hour) <br> + RecurringCommitmentForBillingPeriod (for that hour)</p><p><strong>Simple example</strong></p><p>Say you bought a Partial Upfront Savings Plan with:</p><ul><li>Total hourly commitment: <strong>$0.50/hour</strong></li><li>Split: $0.15/hour comes from your amortized upfront payment, $0.35/hour is billed recurringly(from the above examples of saving plan)</li></ul><p>AmortizedUpfrontCommitmentForBillingPeriod = $0.15<br>RecurringCommitmentForBillingPeriod = $0.35<br>TotalCommitmentToDate = $0.15 + $0.35 = $0.50</p><pre>┌──────────────────────────┬───────────────────────────┬──────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────┬──────────────────────────────────────┐<br>│ lineItem/UsageStartDate  │ lineItem/LineItemType     │ savingsPlan/AmortizedUpfrontCommitmentForBillingPeriod   │ savingsPlan/RecurringCommitmentForBillingPeriod     │ savingsPlan/TotalCommitmentToDate    │<br>├──────────────────────────┼───────────────────────────┼──────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────┼──────────────────────────────────────┤<br>│   2026-01-01T00:00Z      │ SavingsPlanRecurringFee   │                          $0.15                           │                       $0.35                         │                $0.50                 │<br>│   2026-01-01T01:00Z      │ SavingsPlanRecurringFee   │                          $0.15                           │                       $0.35                         │                $0.50                 │<br>│   2026-01-01T02:00Z      │ SavingsPlanRecurringFee   │                          $0.15                           │                       $0.35                         │                $0.50                 │<br>└──────────────────────────┴───────────────────────────┴──────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┴──────────────────────────────────────┘</pre><h3>Cost Categories Details</h3><p>Cost Categories columns in AWS Cost and Usage Reports (CUR) are used to group and classify AWS costs based on business rules that you define.</p><p>Unlike tags (which are attached directly to resources), Cost Categories are logical groupings created in AWS Billing.</p><p>Once you define a Cost Category (for example, Project, Team, or Environment), AWS automatically adds it as a column in CUR.</p><h4>Common Cost Categories Columns</h4><ul><li>costCategory/Project</li><li>costCategory/Team</li><li>costCategory/Environment</li></ul><h4>costCategory/Project</h4><p>Represents cost grouped by project-level classification.</p><p>You define project rules such as:</p><ul><li>alpha</li><li>beta</li><li>migration</li><li>analytics</li></ul><p>These values appear under this column.</p><p>Example</p><p>Suppose you define:</p><pre>┌──────────┬─────────┐<br>│ Resource │ Project │<br>├──────────┼─────────┤<br>│ EC2-A    │ alpha   │<br>│ EC2-B    │ beta    │<br>└──────────┴─────────┘</pre><p>CUR output:</p><pre>┌──────────────────────┬─────────┐<br>│ Column               │ Value   │<br>├──────────────────────┼─────────┤<br>│ costCategory/Project │ alpha   │<br>└──────────────────────┴─────────┘</pre><h4>costCategory/Team</h4><p>Represents cost grouped by team ownership.</p><p>Common values include:</p><ul><li>Marketing</li><li>Engineering</li><li>Finance</li><li>Data</li></ul><p>Example</p><pre>┌──────────────┬─────────────┐<br>│ Resource     │ Team        │<br>├──────────────┼─────────────┤<br>│ S3 Bucket    │ Marketing   │<br>│ EC2 Instance │ Engineering │<br>└──────────────┴─────────────┘</pre><p>CUR output:</p><pre>┌───────────────────┬─────────────┐<br>│ Column            │ Value       │<br>├───────────────────┼─────────────┤<br>│ costCategory/Team │ Engineering │<br>└───────────────────┴─────────────┘</pre><h4>costCategory/Environment</h4><p>Represents cost grouped by deployment environment.</p><p>Typical values include:</p><ul><li>Development</li><li>Testing</li><li>Staging</li><li>Production</li></ul><p>Example</p><pre>┌──────────┬─────────────┐<br>│ Resource │ Environment │<br>├──────────┼─────────────┤<br>│ EC2-A    │ Development │<br>│ EC2-B    │ Production  │<br>└──────────┴─────────────┘</pre><p>CUR output:</p><pre>┌──────────────────────────┬────────────┐<br>│ Column                   │ Value      │<br>├──────────────────────────┼────────────┤<br>│ costCategory/Environment │ Production │<br>└──────────────────────────┴────────────┘</pre><h3>Discount Details</h3><p>Discount columns in AWS Cost and Usage Reports (CUR) show the discount amount applied to a billing line item.</p><p>These columns appear only if your AWS account receives discounts during the billing period.</p><h4>Discount Columns</h4><ul><li>discount/BundledDiscount</li><li>discount/TotalDiscount</li></ul><h4>discount/BundledDiscount</h4><p>Represents the discount applied because multiple AWS services are bundled together or because one AWS service includes another service at no additional cost.</p><p>AWS automatically applies this discount when eligible services qualify for bundled pricing.</p><p>Example 1: AWS Shield Advanced</p><p>Suppose:</p><ul><li>You use AWS Shield Advanced.</li><li>AWS provides AWS WAF usage as part of the Shield Advanced subscription.</li><li>The WAF usage normally costs $20, but AWS waives this charge because it is included with Shield Advanced.</li></ul><pre>┌──────────────────┬─────────┐<br>│ Item             │ Value   │<br>├──────────────────┼─────────┤<br>│ WAF Usage Cost   │ $20     │<br>│ Bundled Discount │ -$20    │<br>│ Final Cost       │ $0      │<br>└──────────────────┴─────────┘</pre><p>CUR entry:</p><pre>┌──────────────────────────┬─────────┐<br>│ Column                   │ Value   │<br>├──────────────────────────┼─────────┤<br>│ discount/BundledDiscount │ -$20    │<br>└──────────────────────────┴─────────┘</pre><h4>discount/TotalDiscount</h4><p>Represents the total discount applied to a billing line item.</p><p>It is the sum of all applicable discount columns for that line item.</p><p>Formula: <strong>TotalDiscount = Sum of all discount columns</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95559cee1fe" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/understanding-aws-cost-and-usage-report-cur-c95559cee1fe">Understanding AWS Cost and Usage Report (CUR)</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Servlets to Spring Boot: Understanding the Evolution of Java Backend Development]]></title>
            <link>https://medium.com/@farhinbashira/from-servlets-to-spring-boot-understanding-the-evolution-of-java-backend-development-1d294a2716cd?source=rss-8d2e3a58af0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d294a2716cd</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[servlet]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Bashira Farhin]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 18:07:09 GMT</pubDate>
            <atom:updated>2026-08-08T17:20:29.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*jDp9puJ1HH3bbzabVCWMGg.jpeg" /></figure><h3>Servlet</h3><p>A <strong>Servlet</strong> is a Java class that handles client requests, processes them, and returns the response.</p><p>We can create different servlets for different purposes:</p><ul><li>One servlet for accepting REST API requests</li><li>Another servlet for accepting SOAP API requests</li><li>Another servlet for handling file uploads</li></ul><p>For example, in Spring MVC, the <strong>DispatcherServlet</strong> is configured by default to handle all APIs using &quot;/*&quot; mapping.</p><p>Servlet classes are known as <strong>Servlet APIs</strong>.</p><p>A <strong>Servlet Container</strong> is responsible for managing servlets.</p><h3>Custom Servlet</h3><p>To create a custom servlet:</p><ul><li>You need to extend the HTTPServlet class.</li><li>You need to override methods like:</li></ul><pre>doGet()<br>doPost()<br>doPut()<br>doDelete()</pre><p>These methods handle different types of HTTP requests.</p><h3>Java Application Without Any Framework</h3><p>Previously, if you wanted to build an application using Java without any framework, you had to create servlet classes that would handle the incoming requests.</p><p>After creating servlets, you needed to map those servlets inside the web.xml file.</p><p>In web.xml, we needed to define:</p><ul><li>What are all the servlets available</li><li>Which APIs each servlet handles</li><li>Which servlet should handle which request</li></ul><p>The request flow was:</p><ol><li>The request first arrives at the <strong>Servlet Container (Tomcat)</strong>.</li><li>The servlet container checks web.xml.</li><li>It identifies which servlet should handle the request.</li><li>It invokes the particular method of that servlet that handles the request.</li></ol><h3>Problems with Servlets</h3><h3>1. web.xml File</h3><p>In Servlet-based applications, everything was configured inside web.xml.</p><p>It contained:</p><ul><li>All servlets</li><li>All servlet mappings</li><li>Which servlet handles which API</li><li>All filters</li><li>All listeners</li></ul><p>For a large application, this became a huge problem because the file could contain thousands of lines of configuration.</p><h3>2. Servlet Class Problem</h3><p>Servlet classes also created problems.</p><p>A servlet can have only one method for each HTTP request type:</p><ul><li>One doGet()</li><li>One doPost()</li><li>One doPut()</li><li>One doDelete()</li></ul><p>But in real applications, we need multiple GET APIs, multiple POST APIs, and so on.</p><p>Because of this limitation, we had to use many if conditions inside methods.</p><p>For example, inside doGet(), we had to check the request path manually:</p><pre>if (request.getPathInfo().equals(&quot;/users&quot;)) {<br>    ...<br>}<br>else if (request.getPathInfo().equals(&quot;/users/1&quot;)) {<br>    ...<br>}</pre><p>The servlet method became responsible for handling multiple APIs.</p><h3>3. Object Creation Problem</h3><p>In Servlets:</p><ul><li>We create objects manually using new.</li><li>Our class decides what objects to create and when to create them.</li></ul><p>This causes:</p><ul><li>Tight coupling</li><li>Hard-to-test code</li><li>Lifecycle management becomes our responsibility</li></ul><h3>4. Unit Testing is Much Harder</h3><p>In Servlets, object creation depends on the Servlet Container.</p><p>Because of this dependency, mocking is not easy and unit testing becomes much harder.</p><h3>5. WAR Deployment Problem</h3><p>With Servlet-based applications:</p><ul><li>We needed to create a WAR file of our application.</li><li>Then deploy it manually on Tomcat.</li></ul><p>This process was time-consuming.</p><h3>Spring Framework / Spring MVC</h3><p>Because of the problems existing in Servlets, the <strong>Spring Framework</strong> was introduced.</p><p>Spring Framework does not support Java 25 yet.</p><p>Spring solved many problems that existed in traditional Servlet-based applications.</p><h3>1. Removing the web.xml Problem</h3><p>Spring introduced <strong>annotation-based configuration</strong>.</p><p>Instead of managing everything manually inside web.xml, we could configure things using annotations.</p><h3>2. Inversion of Control (IoC)</h3><p>IoC is a more flexible way to manage object dependencies and their lifecycle.</p><p>It works through <strong>Dependency Injection</strong>.</p><h3>3. Unit Testing</h3><p>Spring Dependency Injection makes unit testing much easier.</p><h3>4. Easy API Creation</h3><p>Spring made API creation easier.</p><p>We just need to use annotations like:</p><pre>@GetMapping</pre><p>to create GET APIs.</p><p>We can create multiple APIs in the same way.</p><h3>5. Integration</h3><p>Spring makes integration with other technologies easier, such as:</p><ul><li>Hibernate</li><li>Security</li><li>Other frameworks</li></ul><h3>Problems with Spring Framework</h3><p>Although Spring solved many problems that existed with Servlets, Spring itself had some problems.</p><h3>1. Dependency Management Problem</h3><p>While adding dependencies in Spring, we needed to add the dependency along with its version.</p><p>The added dependency should also be compatible with the already existing dependencies.</p><p>So, we needed to manually take care of dependency versions and compatibility.</p><h3>2. WAR Deployment Problem</h3><p>Similar to Servlet-based applications:</p><ul><li>We still needed to create a WAR file of our application.</li><li>Then we had to deploy it on Tomcat manually.</li></ul><p>This process was time-consuming.</p><h3>Spring Boot</h3><p>Because of these problems, <strong>Spring Boot</strong> was introduced.</p><p>Spring Boot follows the software principle:</p><h3>Convention over Configuration</h3><p>This means:</p><p><strong>Prefer sensible defaults (convention) but allow developers to override them (configuration).</strong></p><h3>Convention vs Configuration</h3><h3>Convention</h3><p>Convention means the default behavior that Spring Boot applies automatically.</p><h3>Configuration</h3><p>Configuration means custom settings that override the default behavior.</p><p>You can change the default behavior using:</p><ul><li>application.properties</li><li>application.yml</li><li>Java @Bean definitions</li><li>Custom configuration classes</li></ul><p>Spring Boot assumes that you want the most common setup, so it:</p><ul><li>Auto-configures beans</li><li>Provides default settings</li><li>Detects dependencies and configures them</li><li>Chooses the default server (Tomcat)</li><li>Chooses the default port (8080)</li><li>Uses Jackson as the default JSON library</li><li>Uses Logback as the default logging framework</li></ul><h3>Embedded Server</h3><p>Spring Boot automatically configures the server port by default.</p><p>This follows the convention approach.</p><p>The default port is:</p><pre>8080</pre><p>If we want to override it, we can configure:</p><pre>server.port=8081</pre><p>This is configuration.</p><h3>Auto Configuration</h3><p>Spring Boot automatically configures beans based on classpath dependencies.</p><h3>What is Classpath Dependency?</h3><p>Classpath dependencies mean the JAR files or libraries that exist in your project.</p><p>Examples:</p><ul><li>spring-boot-starter-web</li><li>spring-boot-starter-data-jpa</li><li>spring-boot-starter-security</li></ul><p>When certain libraries are present in your project, Spring Boot automatically creates and configures the required beans.</p><p>You do not need to manually write configuration classes.</p><h3>Auto Configuration Example</h3><h3>Convention</h3><p>Spring Boot checks what is present in the classpath and configures things automatically.</p><p>For example:</p><p>If your dependencies include:</p><pre>spring-boot-starter-data-jpa</pre><p>Spring Boot automatically configures:</p><ul><li>EntityManagerFactory</li><li>HibernateJpaVendorAdapter</li><li>DataSource</li><li>TransactionManager</li><li>Repository scanning</li></ul><p>You do not need to create these beans manually.</p><h3>Configuration</h3><p>You can override or customize auto-configured values using application.properties.</p><p>Example:</p><pre>spring.datasource.url=jdbc:postgresql://localhost:5432/test<br>spring.jpa.show-sql=true<br>spring.jpa.hibernate.ddl-auto=update</pre><h3>Dependency Management</h3><p>Spring Boot provides starter dependencies.</p><p>Examples:</p><ul><li>spring-boot-starter-web</li><li>spring-boot-starter-test</li></ul><p>These starters:</p><ul><li>Automatically select compatible versions</li><li>Prevent dependency conflicts</li><li>Reduce manual work</li></ul><p>You do not need to worry about versions anymore.</p><h3>Spring vs Spring Boot</h3><p>Spring Boot is a layer built on top of Spring that provides:</p><ul><li>Auto Configuration</li><li>Embedded servers</li><li>Opinionated defaults</li><li>Easy project setup through Spring Initializr</li><li>Minimal configuration</li></ul><h3>Spring Framework</h3><p>In Spring, we had to perform manual configuration.</p><p>This included:</p><ul><li>Large XML files</li><li>Manual bean creation</li><li>Manual server setup</li><li>Complex configuration for MVC, JPA, Hibernate, and transactions</li></ul><h3>Server Setup in Spring</h3><p>The server did not come embedded.</p><p>We had to:</p><ul><li>Install an external server like Tomcat, Jetty, or WildFly</li><li>Create a WAR file</li><li>Deploy the application manually</li></ul><h3>Spring Boot</h3><p>In Spring Boot:</p><ul><li>Almost everything is auto-configured.</li><li>We just need to annotate and run.</li><li>No XML configuration is required.</li></ul><h3>Embedded Server in Spring Boot</h3><p>Spring Boot comes with embedded servers:</p><ul><li>Embedded Tomcat</li><li>Embedded Jetty</li><li>Embedded Netty</li></ul><p>We can run the application using:</p><pre>java -jar</pre><p>and deploy it as an executable JAR.</p><h3>Smart Defaults in Spring Boot</h3><p>Spring Boot applies smart defaults.</p><p>For example:</p><p>When we add:</p><pre>spring-boot-starter-web</pre><p>Spring Boot automatically configures:</p><ul><li>DispatcherServlet</li><li>WebMVC</li><li>Jackson</li><li>Tomcat</li><li>Validation</li><li>Logging</li><li>Error handling</li></ul><p>We do not need to configure these manually.</p><h3>Production Ready Defaults</h3><p>Spring Boot provides production-ready defaults like:</p><ul><li>Logging</li><li>Error pages</li><li>Metrics</li></ul><p>Spring Boot provides pre-made dependencies, making it easier to write code.</p><p>Examples:</p><ul><li>spring-boot-starter-web</li><li>spring-boot-starter-data-jpa</li><li>spring-boot-starter-security</li></ul><h3>Cons of Spring Boot</h3><p>Although Spring Boot makes development easier, it also has some disadvantages.</p><h3>1. Less Control</h3><p>Because of auto-configuration, we get less control over configurations.</p><h3>2. Heavy Startup for Small Applications</h3><p>For small applications, Spring Boot can have heavier startup time because it packages many libraries by default.</p><h3>3. Larger JAR Size</h3><p>Spring Boot applications have larger JAR sizes because the embedded server is included.</p><h3>4. Difficult Auto-Configuration Debugging</h3><p>Debugging auto-configuration issues can be difficult because too many auto-configured beans may confuse developers.</p><h3>Application.properties vs Application.yml</h3><p>Spring Boot allows configuration using two formats:</p><ul><li>application.properties</li><li>application.yml</li></ul><p>YAML or .yml is not related to Docker.</p><h3>.properties File</h3><p>Properties files use:</p><ul><li>Flat key-value pairs</li><li>Dot (.) notation to represent hierarchy</li></ul><p>Example:</p><pre>spring.datasource.username=root<br>spring.datasource.password=1234</pre><p>When we want nested configuration, there is a lot of repetition.</p><p>Properties files are:</p><ul><li>Good for small configurations</li><li>Simple</li></ul><p>But they become long and ugly when configurations are deeply nested.</p><h3>Lists in Properties Files</h3><p>For lists, properties files need special syntax.</p><p>Example:</p><pre>spring.profiles.active[0]=dev<br>spring.profiles.active[1]=test</pre><h3>Spring Profiles in Properties Files</h3><p>Spring uses configuration files based on the active profile.</p><p>The active profile is set using:</p><pre>spring.profiles.active=dev</pre><h3>Spring Naming Rule</h3><p>Default configuration file:</p><pre>application.properties</pre><p>Profile-specific configuration files:</p><pre>application-{profile}.properties</pre><p>These files are loaded only when that profile is active.</p><p>Examples:</p><pre>application-dev.properties<br>application-qa.properties<br>application-prod.properties</pre><h3>Multiple Active Profiles</h3><p>Example:</p><pre>spring.profiles.active=prod,dev</pre><p>This activates all mentioned profiles.</p><p>However, the configuration file loaded with higher priority will be the last profile mentioned.</p><p>In this case:</p><pre>application-dev.properties</pre><p>will be loaded.</p><p>If spring.profiles.active is not set:</p><pre>application.properties</pre><p>is used.</p><p>If both are set, priority is given to the user-provided configuration.</p><p>The value in application.properties can be changed from:</p><ul><li>Terminal</li><li>Operating System</li><li>pom.xml</li></ul><p>That is why it is dynamic.</p><h3>Application.yml File</h3><p>YAML files use the YAML format.</p><p>They provide:</p><ul><li>Hierarchical structure</li><li>Clean and structured configuration</li><li>Better readability for complex configurations</li></ul><p>Example:</p><pre>spring:<br>  datasource:<br>    username: root<br>    password: 1234</pre><h3>Lists in YAML</h3><p>YAML supports lists naturally.</p><p>Example:</p><pre>spring:<br>  profiles:<br>    active:<br>      - dev<br>      - test</pre><p>In YAML, you can also use the dot operator to represent hierarchy.</p><p>However, there is no point in using it because YAML was introduced to remove the downside of .properties files.</p><h3>Build Tool</h3><p>Writing code is only part of the work.</p><p>To run an application, we often need to:</p><ul><li>Compile source code</li><li>Download and manage dependencies (libraries)</li><li>Run tests</li><li>Create a final package (JAR, WAR, ZIP, Docker image, etc.)</li><li>Clean old builds</li><li>Deploy the application</li></ul><p>A <strong>build tool</strong> automates all of these tasks.</p><p>Both <strong>Maven</strong> and <strong>Gradle</strong> are build tools.</p><h3>Maven</h3><p>Maven is a build automation tool primarily built for Java projects.</p><p>Later, it was configured to build projects written in other languages as well.</p><p>Maven builds a project using:</p><ul><li>Project Object Model (POM)</li><li>A set of plugins</li></ul><p>Maven is hosted by the <strong>Apache Software Foundation</strong>.</p><p>Initially, it was known as the Jakarta project.</p><h3>Maven Configuration</h3><p>In Maven, configuration is written in XML using:</p><pre>pom.xml</pre><p>Because XML requires many tags, Maven configuration contains a lot of boilerplate.</p><p>For adding a dependency in Maven, we need to use multiple tags.</p><p>Example:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>Maven Performance</h3><p>Maven is slower because it performs a full build from scratch every time we create a build.</p><p>Maven performs compilation every time, even if the input files have not changed.</p><p>Maven does not provide:</p><ul><li>Advanced caching</li><li>Parallel build by default</li></ul><h3>Maven as a Project Management Tool</h3><p>Maven is also a project management tool.</p><p>It helps developers with:</p><ul><li>Build generation</li><li>Dependency resolution</li><li>Documentation</li></ul><p>Maven uses the <strong>POM (Project Object Model)</strong> to achieve this.</p><p>When we run a Maven command:</p><ol><li>Maven looks for pom.xml in the current directory.</li><li>It reads the required configuration from it.</li></ol><p>Before Maven, there was a tool called <strong>Ant</strong>.</p><p>In Ant, we had to define:</p><ul><li>What to do</li><li>How to do it</li></ul><h3>Maven Project Identification</h3><p>groupId and artifactId are used to identify a particular project in Maven Central.</p><p>Every pom.xml is a child of another pom.xml.</p><p>By default, every pom.xml is a child of the <strong>super pom.xml</strong>.</p><h3>Maven Lifecycle</h3><p>Maven has different phases in its lifecycle.</p><p>The lifecycle phases are:</p><ol><li>Validate</li><li>Compile</li><li>Test</li><li>Package</li><li>Verify</li><li>Install</li><li>Deploy</li></ol><h3>Validate</h3><p>Checks the project structure.</p><h3>Compile</h3><p>Compiles the source code.</p><h3>Test</h3><p>Runs tests on the code, such as unit tests.</p><h3>Package</h3><p>Packages the compiled code into:</p><ul><li>JAR</li><li>WAR</li></ul><h3>Verify</h3><p>Checks the integrity of the package.</p><h3>Install</h3><p>Installs the package into the local repository.</p><h3>Deploy</h3><p>Deploys the package into a remote repository.</p><h3>Maven Commands</h3><p>When we run:</p><pre>mvn install</pre><p>It runs every lifecycle step except the last one.</p><p>If you want to run a particular phase, then all previous phases will also run.</p><p>Each phase contains a list of goals/tasks.</p><p>If you want to run a specific goal of a particular phase:</p><ul><li>All goals of previous phases will run.</li><li>Current phase goals before the defined goal will run.</li></ul><h3>Adding Custom Goals in Maven</h3><p>If you want to add a new goal or task to any lifecycle, you can use:</p><pre>&lt;build&gt;<br>&lt;/build&gt;</pre><p>inside the pom.xml file.</p><h3>Gradle</h3><p>Gradle is a build automation tool for multiple programming languages.</p><p>It was primarily built to remove the drawbacks of Maven.</p><p>Gradle introduces a <strong>Java and Groovy-based DSL (Domain Specific Language)</strong> for declaring project configuration.</p><h3>What is DSL?</h3><p>Gradle provides a customized language designed specifically for build configuration.</p><p>You can think of DSL as:</p><ul><li>A special language inside Groovy or Kotlin</li><li>It provides special keywords offered by Gradle</li><li>It is designed to make build configuration easy to describe</li></ul><h3>Examples of Gradle DSL Keywords</h3><p>Some common DSL keywords are:</p><pre>dependencies { }<br>tasks { }<br>repositories { }<br>plugins { }</pre><p>These are <strong>not standard Groovy or Kotlin keywords</strong>. They are Gradle DSL constructs.</p><h3>Advantages of DSL</h3><p>DSL avoids unnecessary boilerplate such as XML tags.</p><p>For example, to add a dependency in Gradle:</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;</pre><p>Since Gradle DSL is based on Groovy/Kotlin, you can write:</p><ul><li>Functions</li><li>Conditions</li><li>Loops</li><li>Variables</li></ul><p>DSL provides:</p><ul><li>Better readability</li><li>Greater flexibility</li><li>Less boilerplate</li><li>The power of a real programming language</li><li>Easier custom builds</li></ul><h3>Gradle Performance</h3><p>Gradle provides better performance because it performs <strong>incremental builds</strong>.</p><p>Gradle remembers the previous build and checks:</p><ul><li>Have the input files changed?</li><li>Have the output files changed?</li></ul><p>If nothing has changed, Gradle skips that task.</p><p>When a new build is triggered, Gradle only builds the newer or updated tasks instead of rebuilding everything.</p><p>It also avoids recompiling when there are no changes in the input files.</p><h3>Gradle Build Workflow</h3><p>Gradle is <strong>task-based</strong>, not <strong>phase-based</strong>.</p><p>It provides several optimization features:</p><ul><li>Daemon</li><li>Caching</li><li>Parallel builds</li></ul><h3>Incremental Builds</h3><p>Incremental builds mean Gradle rebuilds only what has changed.</p><h3>Parallel Builds</h3><p>Parallel builds make multi-module projects faster.</p><p>If your project has multiple independent modules, Gradle can build them simultaneously using multiple CPU cores.</p><p>Example modules:</p><ul><li>user-service</li><li>auth-service</li><li>payment-service</li></ul><p>If these modules do not depend on each other, Gradle builds them in parallel.</p><h3>Build Cache</h3><p>Gradle reuses outputs from previous builds using the build cache.</p><h3>Daemon Process</h3><p>Gradle normally runs a background process called a <strong>daemon</strong>, which stays running in memory.</p><p>This daemon keeps:</p><ul><li>JVM preloaded</li><li>Classes already loaded</li><li>Build scripts parsed</li><li>Configuration cached</li></ul><h3>Without Daemon</h3><p>For every build:</p><ol><li>Start the JVM</li><li>Load Gradle</li><li>Configure the environment</li><li>Start the build</li></ol><h3>With Daemon</h3><p>Gradle reuses the already-running JVM, allowing the build to start immediately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d294a2716cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write clean code?]]></title>
            <link>https://medium.com/@farhinbashira/how-to-write-clean-code-41418720a40a?source=rss-8d2e3a58af0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/41418720a40a</guid>
            <category><![CDATA[professional-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[robert-c-martin]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Bashira Farhin]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 10:27:00 GMT</pubDate>
            <atom:updated>2026-10-11T17:04:52.954Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Based on Clean Code by Robert C. Martin</blockquote><blockquote><em>There are two parts to learning craftsmanship: knowledge and work. You must gain the knowledge of principles, patterns, practices, and heuristics that a craftsman knows, and you must also grind that knowledge into your fingers, eyes, and gut through hard work and practice.</em></blockquote><blockquote><em>— Robert C. Martin</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*tT8V8nCSIYdkiB7HV29M4g.jpeg" /></figure><h3>Table of Contents</h3><p>1. Meaningful Names</p><p>2. Functions</p><p>3. Comments</p><p>4. Formatting</p><p>5. Objects and Data Structures</p><p>6. Error Handling</p><p>7. Boundaries</p><p>8. Unit Tests</p><p>9. Classes</p><p>10. Some Important Coding Principles</p><h3>Meaningful Names</h3><p>The name of a variable, function, or class should answer the big questions:</p><ul><li>Why it exists</li><li>What it does</li><li>How it is used</li></ul><p>Good names reduce the need for comments, improve readability, and make code self-documenting.</p><h3>1. Use Intention-Revealing Names</h3><p>A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, it isn’t doing its job.</p><h3>❌ Bad</h3><pre>int d; // elapsed time in days</pre><h3>✅ Good</h3><pre>int elapsedTimeInDays;<br>int daysSinceCreation;<br>int fileAgeInDays;</pre><h3>❌ Bad</h3><pre>public List&lt;int[]&gt; getThem() {<br>    List&lt;int[]&gt; list1 = new ArrayList&lt;int[]&gt;();<br>for (int[] x : theList)<br>        if (x[0] == 4)<br>            list1.add(x);<br>    return list1;<br>}</pre><h3>✅ Good</h3><pre>public List&lt;Cell&gt; getFlaggedCells() {<br>    List&lt;Cell&gt; flaggedCells = new ArrayList&lt;Cell&gt;();<br>for (Cell cell : gameBoard)<br>        if (cell.isFlagged())<br>            flaggedCells.add(cell);<br>    return flaggedCells;<br>}</pre><p>The code’s complexity didn’t change — only the names did. Yet the second version is instantly understandable.</p><h3>2. Avoid Disinformation</h3><p>Do not leave false clues that obscure the meaning of code.</p><p>For example, don’t call a collection accountList unless it is actually a List which is a data structure.</p><p>Prefer:</p><pre>accounts<br>accountGroup<br>customerAccounts</pre><h3>❌ Hard to Distinguish</h3><pre>XYZControllerForEfficientHandlingOfStrings<br>XYZControllerForEfficientStorageOfStrings</pre><h3>❌ Classic Trap</h3><pre>int a = l;<br>if (O == l)<br>    a = O1;<br>else<br>    l = 01;</pre><p>Lowercase l and uppercase O look dangerously similar to 1 and 0.</p><h3>3. Make Meaningful Distinctions</h3><p>If names must differ, make the difference meaningful.</p><h3>❌ Bad</h3><pre>getActiveAccount();<br>getActiveAccounts();<br>getActiveAccountInfo();</pre><h3>❌ Noise Words</h3><pre>moneyAmount<br>money<br><br>customerInfo<br>customer<br>accountData<br>account<br>theMessage<br>message</pre><p>Avoid meaningless suffixes such as:</p><pre>Info<br>Data<br>Object<br>Manager<br>String</pre><h3>❌ Bad</h3><pre>ProductInfo<br>ProductData<br>NameString</pre><h3>4. Use Pronounceable Names</h3><p>If you cannot pronounce a name, you cannot discuss it effectively.</p><h3>❌ Bad</h3><pre>class DtaRcrd102 {<br>    private Date genymdhms;<br>    private Date modymdhms;<br>    private final String pszqint = &quot;102&quot;;<br>}</pre><h3>✅ Good</h3><pre>class Customer {<br>    private Date generationTimestamp;<br>    private Date modificationTimestamp;<br>    private final String recordId = &quot;102&quot;;<br>}</pre><p>Now team discussions become natural and clear.</p><h3>5. Use Searchable Names</h3><p>Single-letter variables and magic numbers are difficult to search for.</p><h3>❌ Bad</h3><pre>for (int j = 0; j &lt; 34; j++) {<br>    s += (t[j] * 4) / 5;<br>}</pre><h3>✅ Good</h3><pre>int realDaysPerIdealDay = 4;<br>final int WORK_DAYS_PER_WEEK = 5;<br>for (int j = 0; j &lt; NUMBER_OF_TASKS; j++) {<br>    int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;<br>    int realTaskWeeks = realTaskDays / WORK_DAYS_PER_WEEK;<br>}</pre><h3>Rule of Thumb</h3><p>The larger the scope, the more descriptive the name should be.</p><p>Single-letter names are acceptable only in very small local scopes such as loop counters.</p><h3>6. Avoid Encodings</h3><h3>Hungarian Notation</h3><p>Encoding type information into names is outdated.</p><h3>❌ Bad</h3><pre>String strName;<br>int iCount;<br>boolean bIsActive;</pre><h3>✅ Good</h3><pre>String name;<br>int count;<br>boolean isActive;</pre><h3>Member Prefixes</h3><p>Avoid prefixes such as m_.</p><h3>❌ Bad</h3><pre>private String m_dsc;</pre><h3>✅ Good</h3><pre>private String description;</pre><h3>Interfaces and Implementations</h3><p>Avoid interface prefixes such as I.</p><h3>❌ Bad</h3><pre>interface IShapeFactory { }</pre><h3>✅ Good</h3><pre>interface ShapeFactory { }<br>class ShapeFactoryImpl implements ShapeFactory { }</pre><h3>7. Avoid Mental Mapping</h3><p>Readers should not have to translate names mentally.</p><h3>❌ Bad</h3><pre>int c;<br>int d;<br>int x;</pre><h3>✅ Good</h3><pre>int customerCount;<br>int elapsedDays;<br>int coordinateX;</pre><p>The only common exception is very small loop counters such as i, j, and k.</p><h3>8. Class Names</h3><p>Classes should have noun or noun phrase names.</p><h3>✅ Good</h3><pre>Customer<br>WikiPage<br>Account<br>AddressParser</pre><h3>❌ Avoid</h3><pre>Manager<br>Processor<br>Data<br>Info</pre><p>A class name should never be a verb.</p><h3>9. Method Names</h3><p>Methods should have verb or verb phrase names.</p><h3>✅ Good</h3><pre>postPayment();<br>deletePage();<br>save();</pre><h3>Accessors, Mutators, and Predicates</h3><pre>employee.getName();<br>customer.setName(&quot;Alice&quot;);<br>if (paycheck.isPosted()) {<br>    ...<br>}</pre><h3>Prefer Static Factory Methods</h3><pre>Complex fulcrumPoint = Complex.fromRealNumber(23.0);</pre><p>Instead of:</p><pre>Complex fulcrumPoint = new Complex(23.0);</pre><h3>10. Don’t Be Cute</h3><p>Avoid clever, funny, or culture-dependent names.</p><h3>❌ Cute</h3><pre>whack();<br>eatMyShorts();<br>holyHandGrenade();</pre><h3>✅ Clear</h3><pre>kill();<br>abort();<br>deleteItems();</pre><blockquote><em>Say what you mean. Mean what you say.</em></blockquote><h3>11. Pick One Word per Concept</h3><p>Use one consistent term for one concept.</p><h3>❌ Inconsistent</h3><pre>fetchUser();<br>retrieveUser();<br>getUser();</pre><h3>✅ Consistent</h3><pre>getUser();</pre><p>Use the same term everywhere.</p><h3>12. Don’t Pun</h3><p>Don’t use the same word for different concepts.</p><h3>❌ Bad</h3><pre>public int add(int a, int b)<br>public void add(Object element)</pre><p>These methods perform fundamentally different operations.</p><h3>✅ Better</h3><pre>public void insert(Object element)<br>public void append(Object element)</pre><h3>13. Use Solution Domain Names</h3><p>Programmers understand technical terminology.</p><h3>✅ Good</h3><pre>AccountVisitor<br>JobQueue<br>BinaryTree<br>Factory<br>Observer</pre><p>Use established computer science terms when appropriate.</p><h3>14. Use Problem Domain Names</h3><p>When no suitable technical term exists, use business terminology.</p><h3>Examples</h3><pre>PremiumPolicy<br>ClaimSettlement<br>UnderwritingRule</pre><p>Domain-specific names help communicate business intent.</p><h3>15. Add Meaningful Context</h3><p>Names should provide enough context to be understood without requiring surrounding code.</p><h3>❌ Poor Context</h3><pre>street<br>city<br>state</pre><h3>✅ Better</h3><pre>addressStreet<br>addressCity<br>addressState</pre><p>Context can often be supplied through well-designed classes and namespaces.</p><h3>16. Don’t Add Gratuitous Context</h3><p>Avoid unnecessary prefixes and project-specific clutter.</p><p>Assume the application is named <strong>Gas Station Deluxe (GSD)</strong>.</p><h3>❌ Bad</h3><pre>GSDAccountAddress<br>GSDCustomerRecord<br>GSDPaymentProcessor</pre><h3>✅ Good</h3><pre>AccountAddress<br>CustomerRecord<br>PaymentProcessor</pre><h3>Functions</h3><p>Functions are one of the fundamental building blocks of software. Well-written functions are small, focused, easy to understand, and easy to test.</p><blockquote><em>“The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.”</em></blockquote><blockquote><em>— Robert C. Martin</em></blockquote><h3>1. Keep Functions Small</h3><p>Small functions are easier to read, understand, test, and maintain.</p><h3>❌ Too Large</h3><pre>void processOrder() {<br>    validateOrder();<br>    calculatePrice();<br>    processPayment();<br>    updateInventory();<br>    sendEmail();<br>    generateInvoice();<br>}</pre><h3>✅ Better</h3><pre>void processOrder() {<br>    validateOrder();<br>    completePurchase();<br>    notifyCustomer();<br>}</pre><p>Each function should hide lower-level details.</p><h3>2. Minimize Blocks and Indentation</h3><p>Nested code quickly becomes difficult to follow.</p><h3>❌ Deep Nesting</h3><pre>if (user != null) {<br>    if (user.isActive()) {<br>        if (user.hasPermission()) {<br>            process(user);<br>        }<br>    }<br>}</pre><h3>✅ Cleaner</h3><pre>if (!isValidUser(user)) {<br>    return;<br>}<br>process(user);</pre><h3>Rule</h3><ul><li>Keep indentation levels shallow.</li><li>Most blocks should contain a single function call.</li></ul><h3>3. Do One Thing</h3><p>A function should perform one task and do it well.</p><h3>❌ Multiple Responsibilities</h3><pre>void saveUser() {<br>    validateUser();<br>    saveToDatabase();<br>    sendWelcomeEmail();<br>}</pre><h3>✅ Single Responsibility</h3><pre>void saveUser() {<br>    validateUser();<br>    persistUser();<br>}<br>void sendWelcomeEmail() {<br>    ...<br>}</pre><h3>Rule</h3><p>If you can describe a function using “and”, it is probably doing more than one thing.</p><h3>4. One Level of Abstraction per Function</h3><p>Don’t mix high-level business logic with low-level implementation details.</p><h3>❌ Mixed Abstraction</h3><pre>void generateReport() {<br>    fetchData();<br>    formatAsPdf();<br>    outputStream.write(bytes);<br>}</pre><h3>✅ Consistent Abstraction</h3><pre>void generateReport() {<br>    fetchData();<br>    createPdf();<br>    saveReport();<br>}</pre><p>The implementation details stay inside lower-level functions.</p><h3>5. The Stepdown Rule</h3><p>Code should read like a story from top to bottom.</p><h3>Example</h3><pre>generateInvoice() {<br>    validateOrder();<br>    calculateCharges();<br>    createInvoiceFile();<br>}<br>calculateCharges() {<br>    calculateTax();<br>    calculateDiscount();<br>}</pre><p>Readers should understand the flow without jumping around the file.</p><h3>6. Avoid Large Switch Statements</h3><p>Switch statements tend to grow and violate the “Do One Thing” rule.</p><h3>Bad❌</h3><pre>switch (employeeType) {<br>    case MANAGER:<br>        ...<br>    case DEVELOPER:<br>        ...<br>    case TESTER:<br>        ...<br>}</pre><h3>✅ Better</h3><pre>employee.calculatePay();</pre><p>Using polymorphism keeps behavior close to the object that owns it.</p><h3>7. Use Descriptive Names</h3><p>Function names should clearly communicate intent.</p><h3>❌ Bad</h3><pre>doStuff();<br>process();<br>handle();</pre><h3>✅ Good</h3><pre>calculateMonthlySalary();<br>sendPasswordResetEmail();<br>generateInvoice();</pre><p>A good function name often eliminates the need for comments.</p><h3>8. Minimize Function Arguments</h3><p>The ideal number of arguments is:</p><ol><li>Zero (best)</li><li>One</li><li>Two</li><li>Three or more (avoid)</li></ol><h3>✅ Good</h3><pre>user.activate();</pre><h3>Acceptable</h3><pre>saveUser(user);</pre><h3>Less Ideal</h3><pre>saveUser(user, role);</pre><h3>Avoid</h3><pre>saveUser(user, role, department, manager);</pre><h3>9. Avoid Flag Arguments</h3><p>A boolean flag usually means the function does more than one thing.</p><h3>❌ Bad</h3><pre>render(true);</pre><p>What does true mean?</p><h3>✅ Better</h3><pre>renderForSuite();<br>renderForSingleTest();</pre><p>The intent is now obvious.</p><h3>10. Prefer Argument Objects</h3><p>When several arguments belong together, create an object.</p><h3>❌</h3><pre>createCircle(x, y, radius);</pre><h3>✅</h3><pre>createCircle(centerPoint, radius);</pre><p>This reduces complexity and improves readability.</p><h3>11. Avoid Output Arguments</h3><p>Arguments should usually be inputs.</p><h3>❌</h3><pre>appendFooter(report);</pre><p>Is report being modified or used as input?</p><h3>✅</h3><pre>report.appendFooter();</pre><p>The owner of the data performs the action.</p><h3>12. Have No Side Effects</h3><p>Functions should do exactly what their names suggest.</p><h3>❌ Hidden Side Effect</h3><pre>checkPassword(user, password);</pre><p>Internally:</p><pre>checkPassword(...)<br>{<br>    initializeSession();<br>}</pre><p>The function does more than checking a password.</p><h3>✅ Better</h3><pre>checkPasswordAndInitializeSession();</pre><p>Or split the responsibilities completely.</p><h3>13. Command Query Separation</h3><p>A function should either:</p><ul><li>Perform an action (Command)</li><li>Return information (Query)</li></ul><p>But not both.</p><h3>❌ Bad</h3><pre>if (user.activate()) {<br>    ...<br>}</pre><p>The function changes state and returns information.</p><h3>✅ Better</h3><pre>user.activate();<br>if (user.isActive()) {<br>    ...<br>}</pre><h3>14. Prefer Exceptions Over Error Codes</h3><h3>❌ Error Codes</h3><pre>if (deletePage(page) == E_OK) {<br> if (registry.deleteReference(page.name) == E_OK) {<br>  if (configKeys.deleteKey(page.name.makeKey()) == E_OK){<br>    logger.log(&quot;page deleted&quot;);<br>   } else {<br>    logger.log(&quot;configKey not deleted&quot;);<br>   }<br>  } else {<br>    logger.log(&quot;deleteReference from registry failed&quot;);<br>  }<br>} else {<br>    logger.log(&quot;delete failed&quot;);<br>    return E_ERROR;<br>}</pre><h3>✅ Exceptions</h3><pre>try {<br> deletePage(page);<br> registry.deleteReference(page.name);<br> configKeys.deleteKey(page.name.makeKey());<br>}<br>catch (Exception e) {<br> logger.log(e.getMessage());<br>}</pre><p>This keeps the normal flow separate from error handling.</p><h3>15. Extract Try/Catch Blocks</h3><p>Try/catch blocks should not hide business logic.</p><h3>❌</h3><pre>try {<br>    processPayment();<br>    updateInventory();<br>    sendEmail();<br>} catch(Exception e) {<br>    logger.error(e);<br>}</pre><h3>✅</h3><pre>try {<br>    completeOrder();<br>} catch(Exception e) {<br>    handleOrderFailure(e);<br>}</pre><p>Functions become cleaner and easier to read.</p><h3>16. Don’t Repeat Yourself (DRY)</h3><p>Every piece of knowledge should exist in only one place.</p><h3>❌ Duplicate Logic</h3><pre>double taxA = orderA.getPrice() * 0.18;<br>double taxB = orderB.getPrice() * 0.18;<br>double taxC = orderC.getPrice() * 0.18;</pre><h3>✅ Extracted logic in one place</h3><pre>double calculateTax(Order order) {<br>    return order.getPrice() * 0.18;<br>}<br>double taxA = calculateTax(orderA);<br>double taxB = calculateTax(orderB);<br>double taxC = calculateTax(orderC);</pre><p>Reuse functions instead of copying code.</p><h3>17. Structured Programming</h3><p>Historically, functions were expected to have:</p><ul><li>One entry point</li><li>One exit point</li></ul><p>Modern code can use early returns when they improve readability.</p><h3>❌ Deep Nesting</h3><pre>if (user != null) {<br>    if (user.isActive()) {<br>        process(user);<br>    }<br>}</pre><h3>✅ Guard Clause</h3><pre>if (user == null) return;<br>if (!user.isActive()) return;<br>process(user);</pre><h3>Comments</h3><h3>Introduction</h3><p>Comments are often used to explain code, but the best code is usually self-explanatory.</p><blockquote><em>“The proper use of comments is to compensate for our failure to express ourselves in code.”</em></blockquote><blockquote><em>— Robert C. Martin</em></blockquote><h3>1. Comments Are a Last Resort</h3><p>Comments exist because we couldn’t express something clearly in code.</p><h3>❌ Using Comments to Explain Confusing Code</h3><pre>// Check if employee can receive full benefits<br>if ((employee.flags &amp; HOURLY_FLAG) &amp;&amp;<br>    (employee.age &gt; 65))</pre><h3>✅ Express the Intent in Code</h3><pre>if (employee.isEligibleForFullBenefits())</pre><p>Good names and well-structured code reduce the need for comments.</p><h3>2. Comments Do Not Make Up for Bad Code</h3><p>Many developers write comments to explain messy code.</p><h3>❌ Bad</h3><pre>// Calculate total after applying all discounts<br>// and special customer adjustments<br>// and promotional offers<br>// 30 lines of confusing code...</pre><h3>✅ Better</h3><pre>double total = calculateFinalPrice(order);</pre><p>Instead of explaining bad code, improve the code itself.</p><blockquote><em>Don’t comment bad code. Rewrite it.</em></blockquote><h3>3. Explain Yourself in Code</h3><p>Code should communicate intent whenever possible.</p><h3>❌</h3><pre>// Check whether customer is premium<br>if (customer.points &gt; 1000)</pre><h3>✅</h3><pre>if (customer.isPremium())</pre><p>The second version explains itself and requires no comment.</p><h3>4. Good Comments</h3><p>Although many comments are unnecessary, some comments provide genuine value.</p><h3>Legal Comments</h3><p>Legal notices, licenses, and copyright information are acceptable.</p><pre>/*<br> * Copyright (C) 2026 Company Name<br> * Licensed under Apache License 2.0<br> */</pre><p>These comments are often required by law or company policy.</p><h3>5. Clarifying Comments</h3><p>Sometimes a comment helps explain something that would otherwise be difficult to understand.</p><h3>Example</h3><pre>// Units are stored in milliseconds<br>long timeout = 30000;</pre><p>Without the comment, the meaning of 30000 may not be obvious.</p><h3>6. Amplification Comments</h3><p>A comment can highlight something important that might otherwise appear insignificant.</p><h3>Example</h3><pre>// Must remain synchronized with billing service API version<br>private static final String API_VERSION = &quot;v3&quot;;</pre><p>The comment explains why the value is important.</p><h3>7. Avoid Redundant Comments</h3><p>Comments that simply repeat the code add noise.</p><h3>❌ Bad</h3><pre>// Increment count by one<br>count++;</pre><h3>❌ Bad</h3><pre>// Return the customer<br>return customer;</pre><p>The reader already understands this from the code itself.</p><h3>8. Avoid Misleading Comments</h3><p>Incorrect comments are worse than no comments.</p><h3>❌ Bad</h3><pre>// Returns all active users<br>List&lt;User&gt; getUsers()</pre><p>If the implementation later changes and returns all users, the comment becomes a lie.</p><h3>Rule</h3><p>Code changes frequently. Comments are often forgotten.</p><p>When code and comments disagree, trust the code.</p><h3>9. Avoid Commented-Out Code</h3><p>Commented-out code creates clutter and confusion.</p><h3>❌ Bad</h3><pre>// calculateLegacyTax();<br>// applyOldDiscount();</pre><p>Version control systems already preserve history.</p><p>Delete unused code instead of commenting it out.</p><h3>10. Use TODO Comments Sparingly</h3><p>TODO comments can be useful reminders for future work.</p><h3>Example</h3><pre>// TODO: Replace temporary implementation with caching layer</pre><p>However, TODO comments should be reviewed regularly and not become permanent.</p><h3>Formatting</h3><h3>Introduction</h3><p>Code formatting is about communication. A developer spends far more time reading code than writing it, so formatting should help readers understand the structure and intent of the program.</p><blockquote><em>“The purpose of formatting is communication.”</em></blockquote><p>Good formatting improves readability, maintainability, and collaboration.</p><h3>1. Format Code Like a Newspaper</h3><p>A source file should read like a newspaper article.</p><ul><li>High-level concepts should appear at the top.</li><li>Details should appear lower in the file.</li><li>Readers should understand the overall story before seeing implementation details.</li></ul><h3>Example</h3><pre>generateInvoice()<br>    ├── validateOrder()<br>    ├── calculateCharges()<br>    └── saveInvoice()</pre><p>The reader sees the big picture first and then drills into the details.</p><h3>2. Use Vertical Spacing to Separate Concepts</h3><p>Blank lines help separate different ideas.</p><h3>✅ Good</h3><pre>private String name;<br>private void validate() {<br>    ...<br>}<br>private void save() {<br>    ...<br>}</pre><p>Related concepts are grouped together while unrelated concepts are separated.</p><h3>3. Keep Related Code Close Together</h3><p>Code that works together should stay together.</p><h3>Example</h3><pre>private int count;<br>private int total;<br>private int average;</pre><p>Variables and methods that are closely related should be easy to find.</p><h3>4. Keep Functions and Files Small</h3><p>Large files are difficult to navigate.</p><h3>Rule</h3><ul><li>Small functions are easier to read.</li><li>Small classes are easier to understand.</li><li>Small files are easier to maintain.</li></ul><h3>5. Use Consistent Formatting</h3><p>Choose a style and follow it everywhere.</p><h3>Example</h3><pre>if (user.isActive()) {<br>    processUser();<br>}</pre><p>Not:</p><pre>if(user.isActive()){<br>processUser();}</pre><p>Consistency is often more important than the specific style chosen.</p><h3>6. Avoid Horizontal Clutter</h3><p>Keep lines reasonably short and easy to scan.</p><h3>❌ Hard to Read</h3><pre>if(user.isActive() &amp;&amp; user.hasPermission() &amp;&amp; user.getDepartment().equals(&quot;Finance&quot;))</pre><h3>✅ Better</h3><pre>if (user.isActive()<br>        &amp;&amp; user.hasPermission()<br>        &amp;&amp; user.isFinanceUser()) {<br>    ...<br>}</pre><h3>7. Follow Team Conventions</h3><p>A project should look like it was written by one person, not twenty.</p><p>Use the same:</p><ul><li>Indentation</li><li>Naming stylea</li><li>Spacing rules</li><li>File organization</li></ul><p>throughout the codebase.</p><h3>Objects and Data Structures</h3><p>There is a reason that we keep our variables private. We don’t want anyone else to depend on them. We want to keep the freedom to change their type or implementation on a whim or an impulse.</p><blockquote><em>“Objects expose behavior and hide data. Data structures expose data and have no significant behavior.”</em></blockquote><blockquote><em>— Robert C. Martin</em></blockquote><h3>1. Data Abstraction</h3><p>Hiding implementation is not just about putting getters and setters in front of variables. It’s about <strong>abstraction</strong> — exposing an interface that lets users manipulate the <em>essence</em> of the data without knowing how it’s implemented.</p><h3>❌ Concrete — Exposes Implementation</h3><pre>public class Point {<br>    public double x;<br>    public double y;<br>}</pre><p>This is clearly implemented in rectangular coordinates, and forces callers to manipulate x and y independently. Even making the variables private with simple getters/setters wouldn&#39;t fix this — it would still expose the implementation.</p><h3>✅ Abstract — Hides Implementation</h3><pre>public interface Point {<br>    double getX();<br>    double getY();<br>    void setCartesian(double x, double y);<br>    double getR();<br>    double getTheta();<br>    void setPolar(double r, double theta);<br>}</pre><p>There is no way to tell whether this is implemented in rectangular or polar coordinates — it might be neither. The methods also enforce an <strong>access policy</strong>: you can read coordinates independently, but you must set them together as an atomic operation.</p><h3>Another Example — Concrete vs Abstract</h3><p><strong>❌ Concrete:</strong></p><pre>public interface Vehicle {<br>    double getFuelTankCapacityInGallons();<br>    double getGallonsOfGasoline();<br>}</pre><p><strong>✅ Abstract:</strong></p><pre>public interface Vehicle {<br>    double getPercentFuelRemaining();<br>}</pre><p>In the concrete version, you can be fairly sure these are just accessors of raw variables. In the abstract version, you have no clue at all about the underlying form of the data — which is exactly the point.</p><blockquote><strong><em>Rule:</em></strong><em> Don’t just add getters and setters blindly. Think carefully about the best way to represent your data in abstract terms.</em></blockquote><h3>2. Data/Object Anti-Symmetry</h3><p>This is the central idea of the chapter:</p><blockquote><strong><em>Objects</em></strong><em> hide their data behind abstractions and expose </em><strong><em>functions</em></strong><em> that operate on that data. </em><strong><em>Data structures</em></strong><em> expose their data and have </em><strong><em>no meaningful functions</em></strong><em>.</em></blockquote><p>These two definitions are virtual opposites of each other.</p><h3>Procedural Style — Data Structures + Functions</h3><pre>public class Square {<br>    public Point topLeft;<br>    public double side;<br>}<br><br>public class Rectangle {<br>    public Point topLeft;<br>    public double height;<br>    public double width;<br>}<br><br>public class Circle {<br>    public Point center;<br>    public double radius;<br>}<br><br>public class Geometry {<br>    public final double PI = 3.141592653589793;<br><br>public double area(Object shape) throws NoSuchShapeException {<br>        if (shape instanceof Square) {<br>            Square s = (Square) shape;<br>            return s.side * s.side;<br>        } else if (shape instanceof Rectangle) {<br>            Rectangle r = (Rectangle) shape;<br>            return r.height * r.width;<br>        } else if (shape instanceof Circle) {<br>            Circle c = (Circle) shape;<br>            return PI * c.radius * c.radius;<br>        }<br>        throw new NoSuchShapeException();<br>    }<br>}</pre><ul><li>✅ <strong>Adding a new function</strong> (e.g. perimeter()) → none of the shape classes need to change.</li><li>❌ <strong>Adding a new shape</strong> → every function in Geometry must change.</li></ul><h3>Object-Oriented Style — Polymorphism</h3><pre>public class Square implements Shape {<br>    private Point topLeft;<br>    private double side;<br>public double area() {<br>        return side * side;<br>    }<br>}<br>public class Rectangle implements Shape {<br>    private Point topLeft;<br>    private double height;<br>    private double width;<br>    public double area() {<br>        return height * width;<br>    }<br>}<br>public class Circle implements Shape {<br>    private Point center;<br>    private double radius;<br>    public final double PI = 3.141592653589793;<br>    public double area() {<br>        return PI * radius * radius;<br>    }<br>}</pre><ul><li>✅ <strong>Adding a new shape</strong> → no existing functions need to change.</li><li>❌ <strong>Adding a new function</strong> (e.g. perimeter()) → every shape class must change.</li></ul><blockquote><em>The things that are hard for OOPs are easy for procedures, and the things that are hard for procedures are easy for OOPs.</em></blockquote><p><strong>Takeaway:</strong> Mature programmers know “everything is an object” is a myth. Sometimes you genuinely want simple data structures with procedures operating on them — choose based on whether your system is more likely to grow new <em>data types</em> or new <em>behaviors</em>.</p><h3>3. The Law of Demeter (Principle of Least Knowledge)</h3><blockquote><strong><em>A module should not know about the internal structure of the objects it works with.</em></strong></blockquote><p>In simple terms:</p><blockquote><strong><em>Tell an object what you want, don’t ask it for another object so you can continue navigating through its internals.</em></strong></blockquote><p>The goal is to <strong>reduce coupling</strong> between classes so that internal implementation details remain hidden.</p><h3>❌ Bad — Train Wreck</h3><pre>String outputDir = ctxt.getOptions()<br>                       .getScratchDir()<br>                       .getAbsolutePath();</pre><p>This code knows that:</p><ul><li>Context has Options</li><li>Options has ScratchDir</li><li>ScratchDir is a File</li><li>File has getAbsolutePath()</li></ul><p>The caller is tightly coupled to the internal structure of multiple objects.</p><p>If the object hierarchy changes, this code also needs to change.</p><h3>❌ Splitting It Doesn’t Help</h3><pre>Options options = ctxt.getOptions();<br>File scratchDir = options.getScratchDir();<br>String outputDir = scratchDir.getAbsolutePath();</pre><p>Although this is easier to read, it still has the same problem.</p><p>The code still depends on:</p><pre>Context<br>   ↓<br>Options<br>   ↓<br>ScratchDir<br>   ↓<br>AbsolutePath</pre><p>Breaking the chain into multiple lines does <strong>not</strong> reduce coupling.</p><h3>✅ Better</h3><p>Hide the navigation inside the object that owns the data.</p><pre>class Context {</pre><pre>    public String getScratchDirPath() {<br>        return options.getScratchDir().getAbsolutePath();<br>    }<br>}</pre><p>Now the caller simply writes:</p><pre>String outputDir = ctxt.getScratchDirPath();</pre><p>The caller no longer needs to know:</p><ul><li>where the path comes from</li><li>how many objects are involved</li><li>whether the implementation changes later</li></ul><p>Only the Context class knows those details.</p><h3>Why Is This Better?</h3><p>Imagine the implementation changes.</p><h3>Before</h3><pre>Context<br>   ↓<br>Options<br>   ↓<br>ScratchDir</pre><h3>After</h3><pre>Context<br>   ↓<br>Configuration<br>   ↓<br>Directories<br>   ↓<br>ScratchDir</pre><h3>Without the Law of Demeter</h3><p>Every caller must be updated because they depend on the object hierarchy.</p><h3>With the Law of Demeter</h3><p>Only Context changes.</p><p>All callers continue using:</p><pre>ctxt.getScratchDirPath();</pre><p>No other code needs modification.</p><h3>4. Hybrids — The Worst of Both Worlds</h3><p>A <strong>hybrid</strong> is half object, half data structure: it has functions that do real work, <em>and</em> public variables or accessors/mutators that expose its internals.</p><pre>// ❌ Hybrid — has both behavior AND exposed internals<br>public class Order {<br>    public double total;          // exposed data<br>    public List&lt;Item&gt; items;      // exposed data<br>public void applyDiscount() { // real behavior<br>        ...<br>    }<br>}</pre><p>This makes it <strong>hard to add new functions</strong> (because the data is tangled with behavior) <strong>and hard to add new data structures</strong> (because behavior is tangled with the data). Avoid creating hybrids — they’re a sign of muddled design.</p><h3>5. Hiding Structure Properly</h3><p>If ctxt is a true object, we shouldn&#39;t ask it about its internals — we should <strong>tell it to do something</strong>.</p><h3>❌ Asking for internals</h3><pre>ctxt.getAbsolutePathOfScratchDirectoryOption();<br>// or<br>ctxt.getScratchDirectoryOption().getAbsolutePath();</pre><p>Neither option feels right — the first risks an explosion of methods on ctxt; the second assumes the returned object is really just a data structure.</p><h3>✅ Telling the object what you actually need</h3><p>Ask: <em>why</em> did we need that absolute path in the first place? Usually it’s to do something further down the line, like:</p><pre>String outFile = outputDir + &quot;/&quot; + className.replace(&#39;.&#39;, &#39;/&#39;) + &quot;.class&quot;;<br>FileOutputStream fout = new FileOutputStream(outFile);<br>BufferedOutputStream bos = new BufferedOutputStream(fout);</pre><p>So instead, tell ctxt to do the whole job:</p><pre>BufferedOutputStream bos = ctxt.createScratchFileStream(classFileName);</pre><p>This lets ctxt hide its internals completely, and the calling function no longer needs to navigate through objects it shouldn&#39;t know about.</p><h3>6. Data Transfer Objects (DTOs)</h3><p>The quintessential data structure: a class with <strong>public variables and no functions</strong>.</p><pre>public class AddressDTO {<br>    public String street;<br>    public String city;<br>    public String state;<br>    public String zip;<br>}</pre><p>DTOs are especially useful when communicating with databases or parsing messages from sockets — often the first stage in translating raw data into application objects.</p><h3>The “Bean” Form</h3><p>A more common variant uses private variables with public getters/setters:</p><pre>public class Address {<br>    private String street;<br>    private String city;<br>    private String state;<br>    private String zip;<br>public Address(String street, String city, String state, String zip) {<br>        this.street = street;<br>        this.city = city;<br>        this.state = state;<br>        this.zip = zip;<br>    }<br>    public String getStreet() { return street; }<br>    public String getCity() { return city; }<br>    public String getState() { return state; }<br>    public String getZip() { return zip; }<br>}</pre><blockquote><em>The quasi-encapsulation of beans makes some OO purists feel better, but usually provides no real benefit over plain public fields.</em></blockquote><h3>7. Active Record</h3><p>Active Records are a special form of DTO: public (or bean-style) variables, plus <strong>navigational methods</strong> like save() and find(), typically mapped directly from database tables.</p><pre>public class UserRecord {<br>    public int id;<br>    public String name;<br>    public String email;<br>public void save() { ... }<br>    public static UserRecord find(int id) { ... }<br>}</pre><h3>❌ Common Mistake</h3><p>Treating an Active Record as if it were a full object by stuffing business rules into it:</p><pre>public class UserRecord {<br>    public int id;<br>    public double balance;<br>public void save() { ... }<br>    // ❌ Business logic doesn&#39;t belong here<br>    public void applyMonthlyInterest() {<br>        balance *= 1.02;<br>    }<br>}</pre><h3>✅ Better</h3><p>Keep the Active Record as a pure data structure, and create a <strong>separate object</strong> to hold business rules:</p><pre>public class UserRecord {<br>    public int id;<br>    public double balance;<br>public void save() { ... }<br>}<br>public class Account {<br>    private UserRecord record;<br>    public Account(UserRecord record) {<br>        this.record = record;<br>    }<br>    public void applyMonthlyInterest() {<br>        record.balance *= 1.02;<br>    }<br>}</pre><h3>Error Handling</h3><h3>by Michael Feathers</h3><p>Things can go wrong — bad input, failed devices, missing files. Error handling is necessary, but if it clutters the code so much that you can’t see what the code actually <em>does</em>, it’s being done wrong.</p><blockquote><em>“Error handling is important, but if it obscures logic, it’s wrong.”</em></blockquote><h3>1. Use Exceptions, Not Return Codes</h3><p>Return codes force the caller to remember to check them every time. Forget once, and the error silently slips through.</p><h3>❌ Bad</h3><pre>int result = openFile(name);<br>if (result == ERROR) {<br>    log(&quot;Could not open file&quot;);<br>} else {<br>    readFile(name);<br>}</pre><h3>✅ Good</h3><pre>try {<br>    readFile(name);<br>} catch (FileException e) {<br>    log(e);<br>}</pre><p>The exception version separates <em>what the code does</em> from <em>what happens when it fails</em>.</p><h3>2. Write Try-Catch-Finally First</h3><p>A try block is like a mini transaction — anything inside it can fail at any point, and the catch must leave things in a safe state. So define that boundary <strong>before</strong> writing the logic inside it.</p><pre>try {<br>    // logic goes here later<br>} catch (FileNotFoundException e) {<br>    throw new StorageException(&quot;file not found&quot;, e);<br>}</pre><p>Once the safety net exists, you can fill in the real logic without worrying about what happens if it fails — the catch already handles that.</p><h3>3. Prefer Unchecked Exceptions</h3><p>Checked exceptions force every method between the throw and the catch to declare them — even ones that don&#39;t care.</p><pre>// Add a checked exception low down...<br>void readFile() throws IOException { }<br><br>// ...and it forces changes all the way up:<br>void loadConfig() throws IOException { }<br>void startApp() throws IOException { }</pre><p>One small change at the bottom ripples through the entire call chain. Unchecked exceptions avoid this — that’s why most modern languages (C#, Python, Ruby) don’t even have checked exceptions.</p><h3>4. Give Exceptions Context</h3><p>A stack trace tells you <em>where</em> it broke. It doesn’t tell you <em>why</em>.</p><h3>❌ Bad</h3><pre>throw new StorageException();</pre><h3>✅ Good</h3><pre>throw new StorageException(&quot;Failed to save user profile for id=42&quot;);</pre><p>Always say what operation failed and why — future you (or whoever’s debugging) will thank you.</p><h3>5. Design Exceptions Around How They’re Caught</h3><p>Don’t make the caller juggle five different exception types for one third-party call.</p><h3>❌ Bad — Repetitive Handling</h3><pre>try {<br>    printer.print(doc);<br>} catch (PaperJamException e) {<br>    log(e);<br>} catch (OutOfInkException e) {<br>    log(e);<br>} catch (OfflineException e) {<br>    log(e);<br>}</pre><p>The caller now knows how the printer works internally. If tomorrow the printer library adds:</p><pre>NetworkTimeoutException<br>DriverFailureException</pre><p>every caller has to change.</p><h3>✅ Good — Wrap Them Into One</h3><pre>try {<br>    printer.print(doc);<br>} catch (PrinterException e) {<br>    log(e);<br>}<br><br>class Printer {<br>    void print(Document doc) {<br>        try {<br>            realPrinter.print(doc);<br>        } catch (PaperJamException | OutOfInkException | OfflineException e) {<br>            throw new PrinterException(e);<br>        }<br>    }<br>}</pre><p>The caller only cares about the abstraction — “The printing operation failed.” It does not need to know whether the reason was paper, ink, network, or driver. To let them know the actual error keep the original exception as the cause</p><p>Wrapping a messy third-party API also makes it easier to swap libraries later or mock it in tests.</p><h3>6. Handle “Errors” That Are Really Normal Cases</h3><p>Sometimes what looks like an error is just a regular business rule — don’t force it through exception handling.</p><h3>❌ Bad</h3><pre>try {<br>    total += getMeals(employee).getCost();<br>} catch (NoMealsFoundException e) {<br>    total += getDefaultMealAllowance();<br>}</pre><h3>✅ Good — Special Case Object</h3><pre>class NoMeals implements Meals {<br>    public double getCost() {<br>        return DEFAULT_MEAL_ALLOWANCE;<br>    }<br>}<br>// caller is now simple, no exception needed:<br>total += getMeals(employee).getCost();</pre><p>getMeals() just returns a NoMeals object instead of throwing — the caller never has to know the difference. This is called the <strong>Special Case Pattern</strong>.</p><h3>7. Don’t Return Null</h3><p>Returning null pushes the burden of checking onto every caller — forever.</p><h3>❌ Bad</h3><pre>List&lt;Employee&gt; employees = getEmployees();<br>if (employees != null) {<br>    for (Employee e : employees) {<br>        totalPay += e.getPay();<br>    }<br>}</pre><h3>✅ Good — Return an Empty List Instead</h3><pre>List&lt;Employee&gt; employees = getEmployees(); // never returns null<br>for (Employee e : employees) {<br>    totalPay += e.getPay();<br>}<br>public List&lt;Employee&gt; getEmployees() {<br>    if (noEmployees) return Collections.emptyList();<br>    ...<br>}</pre><p>No null check needed — the loop just doesn’t run if the list is empty.</p><h3>8. Don’t Pass Null</h3><p>Passing null into a method is even worse than returning it — it just shifts the crash somewhere else.</p><pre>calculator.distance(null, point2); // boom — NullPointerException</pre><p>There’s rarely a good way to recover once null sneaks in. The simplest rule: <strong>treat </strong><strong>null as a bug</strong>, not a valid argument, and avoid passing it in the first place.</p><h3>Boundaries</h3><h3>by James Grenning</h3><p>We rarely control all the code in our systems — we use third-party packages, open source libraries, or components built by other teams. This chapter covers how to integrate that foreign code cleanly without letting it leak into and control our own design.</p><h3>1. Be Careful with Third-Party Interfaces</h3><p>Third-party libraries are built for broad use, so their interfaces often expose <strong>more power than you actually want</strong>.</p><h3>❌ Bad — Passing a Raw Map Around</h3><pre>Map&lt;String, Sensor&gt; sensors = new HashMap&lt;&gt;();<br>// somewhere else in the code...<br>Sensor s = sensors.get(sensorId);</pre><p>Anyone holding this Map can call .clear(), add the wrong type, or remove items — even if your design never intended that. And this sensors.get(...) pattern ends up copy-pasted everywhere.</p><h3>✅ Good — Wrap It in Your Own Class</h3><pre>public class Sensors {<br>    private Map&lt;String, Sensor&gt; sensors = new HashMap&lt;&gt;();<br>public Sensor getById(String id) {<br>        return sensors.get(id);<br>    }<br>}</pre><p>Now nobody outside Sensors even knows a Map is involved. If you ever swap HashMap for something else, only this one class changes.</p><blockquote><strong><em>Rule:</em></strong><em> Don’t pass boundary interfaces (like </em><em>Map) around your system. Keep them hidden inside one class, and never accept or return them from public APIs.</em></blockquote><h3>2. Explore Unfamiliar Libraries with “Learning Tests”</h3><p>Learning a new library <em>and</em> integrating it into your app at the same time is hard to debug — you can’t tell if a bug is yours or theirs.</p><p><strong>Solution:</strong> Write small tests that just explore the library’s behavior — separate from your real code.</p><pre>@Test<br>public void loggerWritesToConsole() {<br>    Logger logger = Logger.getLogger(&quot;MyLogger&quot;);<br>    logger.removeAllAppenders();<br>    logger.addAppender(new ConsoleAppender(<br>        new PatternLayout(&quot;%p %m%n&quot;), ConsoleAppender.SYSTEM_OUT));<br>logger.info(&quot;hello&quot;); // confirms our understanding of the API<br>}</pre><p>These are called <strong>learning tests</strong> — small, focused experiments that confirm “this is how the library actually behaves,” before you build real logic on top of it.</p><h3>Why Learning Tests Are Worth It</h3><ul><li>They’re <strong>free</strong> — you had to learn the API anyway; might as well write it down as a test.</li><li>They act as an <strong>early warning system</strong> — if you upgrade the library and a learning test breaks, you know immediately that its behavior changed, before it breaks your real code.</li></ul><h3>3. Code Against Interfaces That Don’t Exist Yet</h3><p>Sometimes you need to start building before another team has even finished designing their API.</p><p><strong>Solution:</strong> Define the interface <strong>you wish you had</strong>, and build against that.</p><pre>public interface Transmitter {<br>    void transmit(double frequency, DataStream data);<br>}</pre><p>Your code stays clean and expressive, built entirely around an interface you control. Once the real API is ready, write an <strong>Adapter</strong> that bridges the gap:</p><pre>public class TransmitterAdapter implements Transmitter {<br>    private final RealTransmitterAPI realApi;<br>public void transmit(double frequency, DataStream data) {<br>        realApi.setFrequency(frequency);<br>        realApi.sendAnalogData(data);<br>    }<br>}</pre><p>Only the Adapter needs to change if the real API changes later — everything else stays untouched. This also gives you a clean seam for testing: swap in a FakeTransmitter to test your own logic without touching the real system at all.</p><h3>4. Keep Boundaries Clean</h3><p>The common thread across all of this: <strong>minimize the number of places your code touches third-party APIs directly.</strong></p><ul><li><strong>Wrap it</strong> (like the Sensors example) when you&#39;re hiding a library&#39;s interface.</li><li><strong>Adapt it</strong> (like the Transmitter example) when you&#39;re bridging to an API that&#39;s still evolving or out of your control.</li></ul><p>Either way:</p><ul><li>Your code reads more clearly, in your own vocabulary.</li><li>Usage of the third-party code stays consistent across your app.</li><li>When the library changes, you have <strong>one place</strong> to fix — not a hundred.</li></ul><h3>Unit Tests</h3><p>Our profession has come a long way. Before TDD, “testing” often meant writing throwaway driver code, running it once manually, and deleting it. Today, automated unit tests are expected to cover virtually every part of the production code.</p><blockquote><em>“Test code is just as important as production code. It is not a second-class citizen.”</em></blockquote><h3>1. The Three Laws of TDD</h3><ol><li>You may <strong>not write production code</strong> until you’ve written a failing unit test.</li><li>You may <strong>not write more of a test</strong> than is sufficient to fail (not compiling counts as failing).</li><li>You may <strong>not write more production code</strong> than is sufficient to pass the currently failing test.</li></ol><p>These three laws lock you into a tight cycle — tests and production code are written together, with tests just seconds ahead. The result: thousands of tests, covering nearly all production code, over time.</p><h3>2. Keep Tests as Clean as Production Code</h3><p>Some teams treat test code as “quick and dirty,” with messy names and tangled logic — as long as it passes and gives coverage. This is a trap.</p><h3>Why Dirty Tests Are Dangerous</h3><ul><li>Production code evolves → tests must change with it.</li><li>The dirtier the tests, the <strong>harder they are to change</strong>.</li><li>Eventually, maintaining the test suite costs more than writing new features.</li><li>Teams often respond by <strong>discarding the test suite</strong> entirely.</li><li>Without tests, fear of change creeps in → code stops being cleaned up → code rots.</li></ul><blockquote><em>Dirty tests are equivalent to — or worse than — no tests at all.</em></blockquote><h3>3. Tests Enable the “-ilities”</h3><p>Unit tests are what make production code flexible, maintainable, and reusable. The reason is simple:</p><ul><li><strong>With tests</strong> → you can change code without fear of breaking it.</li><li><strong>Without tests</strong> → every change is a potential undetected bug, so you avoid touching the code at all.</li></ul><h3>Classes</h3><p>Writing clean lines and functions isn’t enough — code isn’t truly clean until we’ve organized it well at a higher level too. This chapter covers how to design clean classes.</p><blockquote><em>“The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that.”</em></blockquote><h3>1. Class Organization</h3><p>Standard convention for ordering the contents of a class:</p><ul><li>Public static constants</li><li>Private static variables</li><li>Private instance variables</li><li>Public functions</li><li>Private utilities (placed right after the public function that uses them)</li></ul><p>This follows the <strong>stepdown rule</strong> — the class reads top-to-bottom like a newspaper article, with high-level concepts first and details below.</p><h3>2. Encapsulation</h3><p>Keep variables and utility functions <strong>private</strong> by default. Loosening that to protected or package-scope is sometimes necessary — usually so a test in the same package can reach them — but it should always be a <strong>last resort</strong>, not a first choice.</p><h3>3. Classes Should Be Small</h3><p>With functions, size is measured in lines. With classes, size is measured in <strong>responsibilities</strong> — not method count.</p><h3>❌ Too Many Responsibilities (a “God Class”)</h3><pre>public class SuperDashboard extends JFrame implements MetaDataUser {<br>    public Component getLastFocusedComponent() { ... }<br>    public void setLastFocused(Component lastFocused) { ... }<br>    public int getMajorVersionNumber() { ... }<br>    public int getMinorVersionNumber() { ... }<br>    public int getBuildNumber() { ... }<br>    // ...65 more methods covering UI state, projects, menus, file management...<br>}</pre><h3>4. The Single Responsibility Principle (SRP)</h3><blockquote><em>A class should have </em><strong><em>one, and only one, reason to change.</em></strong></blockquote><p>SuperDashboard has two reasons to change:</p><ol><li>Version info updates with every release.</li><li>Swing/GUI behavior changes when the UI changes.</li></ol><h3>✅ Extract the Unrelated Responsibility</h3><pre>public class Version {<br>    public int getMajorVersionNumber() { ... }<br>    public int getMinorVersionNumber() { ... }<br>    public int getBuildNumber() { ... }<br>}</pre><p>Now Version is small, focused, and — as a bonus — reusable in other applications.</p><h3>5. Cohesion</h3><blockquote><em>The more a method uses a class’s own instance variables, the more cohesive it is to that class.</em></blockquote><h3>✅ A Highly Cohesive Class</h3><pre>public class Stack {<br>    private int topOfStack = 0;<br>    List&lt;Integer&gt; elements = new LinkedList&lt;Integer&gt;();<br><br>    public int size() {<br>        return topOfStack;<br>    }<br>    public void push(int element) {<br>        topOfStack++;<br>        elements.add(element);<br>    }<br>    public int pop() throws PoppedWhenEmpty {<br>        if (topOfStack == 0) throw new PoppedWhenEmpty();<br>        int element = elements.get(--topOfStack);<br>        elements.remove(topOfStack);<br>        return element;<br>    }<br>}</pre><p>Almost every method uses both topOfStack and elements — this class hangs together as a single logical unit.</p><h3>When Cohesion Drops — Split the Class</h3><p>If you find a growing number of instance variables that are only used by a <em>subset</em> of methods, that’s a sign a second class is hiding inside the first.</p><pre>// ❌ Warning sign: some methods never touch variableC, variableD<br>public class Report {<br>    private String title;<br>    private List&lt;String&gt; rows;<br>    private String footerFormat;     // only used by 2 of 8 methods<br>    private String footerEncoding;   // only used by the same 2 methods<br>}<br><br><br>// ✅ Extract the related methods + variables into their own class<br>public class ReportFooter {<br>    private String format;<br>    private String encoding;<br>    // methods that use format/encoding<br>}</pre><blockquote><strong><em>Rule:</em></strong><em> If a few methods want to share certain variables, that’s a class in its own right. When classes lose cohesion, split them.</em></blockquote><h3>6. Breaking Up “God Functions” Naturally Produces More Classes</h3><p>Splitting a large function into smaller ones often forces a choice: pass shared variables around as arguments, or promote them to instance variables. Promoting them to instance variables can hurt the <em>original</em> class’s cohesion — which is the signal to <strong>extract a new class</strong> for those functions and variables together.</p><h3>Example: Splitting a Monolithic Program</h3><p>A single 60-line main() method that mixes prime-number generation with page-formatted printing can be split into three focused classes:</p><pre>public class PrimePrinter {<br>    public static void main(String[] args) {<br>        int[] primes = PrimeGenerator.generate(1000);<br>        RowColumnPagePrinter printer =<br>            new RowColumnPagePrinter(50, 4, &quot;The First 1000 Primes&quot;);<br>        printer.print(primes);<br>    }<br>}<br><br>public class PrimeGenerator {<br>    public static int[] generate(int n) { ... }<br>}<br><br>public class RowColumnPagePrinter {<br>    public void print(int[] data) { ... }<br>}</pre><p>Each class now has exactly <strong>one reason to change</strong>:</p><ul><li>PrimePrinter — changes if how the program is invoked changes.</li><li>RowColumnPagePrinter — changes if output formatting changes.</li><li>PrimeGenerator — changes if the prime-finding algorithm changes.</li></ul><h3>7. Organizing for Change (Open-Closed Principle)</h3><blockquote><em>Classes should be </em><strong><em>open for extension, but closed for modification.</em></strong></blockquote><h3>❌ A Class That Must Be “Opened” for Every New Feature</h3><pre>public class Sql {<br>    public Sql(String table, Column[] columns) { ... }<br>    public String create() { ... }<br>    public String insert(Object[] fields) { ... }<br>    public String selectAll() { ... }<br>    public String findByKey(String keyColumn, String keyValue) { ... }<br>    public String select(Criteria criteria) { ... }<br>    // adding &quot;update&quot; support means editing this same class<br>}</pre><p>Every new SQL statement type — or any tweak to an existing one — means re-opening this class and re-testing the whole thing.</p><h3>✅ Split by Responsibility, Closed to Modification</h3><pre>abstract public class Sql {<br>    public Sql(String table, Column[] columns) { }<br>    abstract public String generate();<br>}<br><br>public class CreateSql extends Sql {<br>    @Override public String generate() { ... }<br>}<br>public class SelectSql extends Sql {<br>    @Override public String generate() { ... }<br>}<br>public class InsertSql extends Sql {<br>    @Override public String generate() { ... }<br>}</pre><p>Now, adding update support means adding a brand-new UpdateSql subclass — <strong>no existing class needs to change.</strong></p><pre>public class UpdateSql extends Sql {<br>    @Override public String generate() { ... }<br>}</pre><ul><li>Each class is simpler and faster to understand.</li><li>Each class can be tested in isolation.</li><li>New features extend the system instead of modifying it.</li></ul><h3>8. Isolating from Change (Dependency Inversion Principle — DIP)</h3><blockquote><strong><em>High-level classes should depend on abstractions (interfaces), not concrete implementations.</em></strong></blockquote><p>In simple terms:</p><blockquote><strong><em>Depend on “what something can do” instead of “how it does it.”</em></strong></blockquote><p>This makes your code easier to test, maintain, and extend.</p><h3>❌ Bad — Depending on a Concrete Class</h3><p>Suppose you’re building a notification system.</p><pre>class EmailService {<br>    void send(String message) {<br>        System.out.println(&quot;Sending Email: &quot; + message);<br>    }<br>}<br><br>class Notification {<br>    private EmailService emailService = new EmailService();<br>    void notifyUser(String message) {<br>        emailService.send(message);<br>    }<br>}</pre><h3>What’s the problem?</h3><p>Notification is tightly coupled to EmailService.</p><p>If tomorrow you want to send:</p><ul><li>SMS</li><li>WhatsApp</li><li>Push Notifications</li></ul><p>you’ll have to modify the Notification class.</p><h3>✅ Better — Depend on an Interface</h3><p>Create an abstraction.</p><pre>interface MessageService {<br>    void send(String message);<br>}</pre><p>Provide different implementations.</p><pre>class EmailService implements MessageService {<br>public void send(String message) {<br>        System.out.println(&quot;Sending Email: &quot; + message);<br>    }<br>}<br><br>class SmsService implements MessageService {<br>public void send(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}</pre><p>Now inject the dependency.</p><pre>class Notification {<br>private MessageService messageService;<br>    Notification(MessageService messageService) {<br>        this.messageService = messageService;<br>    }<br>    void notifyUser(String message) {<br>        messageService.send(message);<br>    }<br>}</pre><p>Using It</p><h4>Send Email</h4><pre>MessageService service = new EmailService();<br>Notification notification = new Notification(service);<br>notification.notifyUser(&quot;Order Placed&quot;);</pre><h4>Send SMS</h4><pre>MessageService service = new SmsService();<br>Notification notification = new Notification(service);<br>notification.notifyUser(&quot;Order Placed&quot;);</pre><p>Notice that <strong>Notification never changes</strong>.</p><p>Only the implementation you pass changes.</p><h3>Why Is This Better?</h3><p>Suppose your application originally sends emails.</p><p>Later, the requirement changes to send SMS.</p><h3>Without DIP</h3><p>You modify:</p><pre>Notification</pre><h3>With DIP</h3><p>You simply create:</p><pre>SmsService implements MessageService</pre><p>No changes are needed in Notification.</p><h3>Important Coding Principles</h3><h4>1. DRY — Don’t Repeat Yourself</h4><p><strong>Principle:</strong> Avoid duplicating the same logic in multiple places. Extract common logic into reusable functions or methods.</p><p><strong>Problem:</strong></p><pre>def create_user(email):<br>    if &quot;@&quot; not in email or len(email) &gt; 254:<br>        raise ValueError(&quot;Invalid email&quot;)<br><br>def update_user(email):<br>    if &quot;@&quot; not in email or len(email) &gt; 254:<br>        raise ValueError(&quot;Invalid email&quot;)<br><br>def invite_user(email):<br>    if &quot;@&quot; not in email or len(email) &gt; 254:<br>        raise ValueError(&quot;Invalid email&quot;)</pre><p>If the email rule changes (for example, the maximum length), we must update every function.</p><p><strong>Improved code:</strong></p><pre>def validate_email(email):<br>    if &quot;@&quot; not in email or len(email) &gt; 254:<br>        raise ValueError(&quot;Invalid email&quot;)<br><br>def create_user(email):<br>    validate_email(email)<br><br>def update_user(email):<br>    validate_email(email)<br><br>def invite_user(email):<br>    validate_email(email)</pre><p><strong>Benefit:</strong> Changes are made in one place, reducing duplication and the risk of inconsistent behavior.</p><h4>2. KISS — Keep It Simple, Stupid</h4><p><strong>Principle:</strong> Prefer the simplest solution that correctly solves the problem.</p><p><strong>Problem:</strong></p><pre>def has_items(items):<br>    if len(items) &gt; 0:<br>        return True<br>    else:<br>        return False</pre><p>The condition and branches are unnecessary because the expression already produces a Boolean.</p><p><strong>Improved code:</strong></p><pre>def has_items(items):<br>    return len(items) &gt; 0</pre><p><strong>Benefit:</strong> Less code to read and maintain, with fewer unnecessary operations.</p><h4>3. YAGNI — You Aren’t Gonna Need It</h4><p><strong>Principle:</strong> Don’t implement functionality until there is a real requirement for it.</p><p><strong>Problem:</strong></p><p>An application currently stores its data in one SQLite file, but a developer builds support for MySQL, PostgreSQL, and MongoDB, plus a caching layer, in anticipation of possible future requirements.</p><p><strong>Improved approach:</strong></p><p>Implement the SQLite storage first. Add another database or a cache when the requirement actually arises.</p><p><strong>Benefit:</strong> Less unnecessary code, fewer bugs, and lower maintenance costs.</p><h4>4. SOLID — Five Object-Oriented Design Principles</h4><p>SOLID is a collection of five principles for designing maintainable and extensible object-oriented software.</p><p><strong>S — SRP: Single Responsibility Principle</strong></p><p><strong>Principle:</strong> A class should have one main responsibility and one main reason to change.</p><p><strong>Problem:</strong></p><pre>class BillingService:<br>    def calculate_discount(self, price):<br>        return price * 0.30<br><br>   def save_to_database(self, bill):<br>        pass<br><br>    def send_email(self, bill):<br>        pass</pre><p>This class handles discount calculation, database storage, and email notifications. A change to any of these responsibilities can require modifying the same class.</p><p><strong>Improved code:</strong></p><pre>class DiscountCalculator:<br>    def calculate(self, price):<br>        return price * 0.30<br><br>class BillRepository:<br>    def save(self, bill):<br>        pass<br><br>class EmailNotifier:<br>    def send(self, bill):<br>        pass</pre><p>Each class now has a clear responsibility.</p><p><strong>Benefit:</strong> Changes are isolated. Database changes are less likely to affect discount calculations, and each class can be tested independently.</p><p><strong>O — OCP: Open/Closed Principle</strong></p><p><strong>Principle:</strong> Software components should be open for extension but closed for modification.</p><p>This means new behavior should often be added through new implementations instead of repeatedly changing existing, stable logic.</p><p><strong>Problem:</strong></p><pre>def calculate_discount(service, price):<br>    if service == &quot;CloudFront&quot;:<br>        return price * 0.30<br>    elif service == &quot;WAF&quot;:<br>        return price * 0.10</pre><p>Adding another service requires modifying this function and adding another condition. As services grow, the function becomes harder to maintain.</p><p><strong>Improved code:</strong></p><pre>class Discount:<br>    def calculate(self, price):<br>        raise NotImplementedError<br><br>class CloudFrontDiscount(Discount):<br>    def calculate(self, price):<br>        return price * 0.30<br><br>class WAFDiscount(Discount):<br>    def calculate(self, price):<br>        return price * 0.10<br><br>class NewServiceDiscount(Discount):<br>    def calculate(self, price):<br>        return price * 0.20</pre><p>The new service can be introduced as a new implementation without changing the existing discount classes.</p><p><strong>Benefit:</strong> New functionality can be added with less risk of breaking existing behavior.</p><p><strong>Note:</strong> The calling code must also use the common interface or abstraction for this design to deliver its full benefit.</p><p><strong>L — LSP: Liskov Substitution Principle</strong></p><p><strong>Principle:</strong> An object of a subtype should be usable wherever its parent type is expected without breaking the program’s expected behavior.</p><p><strong>Problem:</strong></p><pre>class Bird:<br>    def fly(self):<br>        pass<br><br>class Sparrow(Bird):<br>    def fly(self):<br>        print(&quot;Flying&quot;)<br><br>class Penguin(Bird):<br>    def fly(self):<br>        raise Exception(&quot;Penguins cannot fly&quot;)</pre><p>Code that expects every Bird to fly will fail when it receives a Penguin.</p><p>The problem is that the parent class promises behavior that not every subtype can provide.</p><p><strong>Improved code:</strong></p><pre>class Bird:<br>    pass<br><br>class FlyingBird(Bird):<br>    def fly(self):<br>        print(&quot;Flying&quot;)<br><br>class Sparrow(FlyingBird):<br>    pass<br><br>class Penguin(Bird):<br>    pass</pre><p>Now, only birds that support flying belong to the FlyingBird abstraction.</p><p><strong>Benefit:</strong> Subtypes behave as callers expect, reducing unexpected errors and making polymorphic code more reliable.</p><p><strong>I — ISP: Interface Segregation Principle</strong></p><p><strong>Principle:</strong> Prefer small, focused interfaces over large interfaces that force classes to implement methods they do not need.</p><p><strong>Problem:</strong></p><pre>class Machine:<br>    def print_document(self):<br>        pass<br><br>   def scan_document(self):<br>        pass<br><br>    def fax_document(self):<br>        pass</pre><p>A basic printer that cannot scan or fax would still be expected to implement all three methods.</p><p><strong>Improved code:</strong></p><pre>class Printer:<br>    def print_document(self):<br>        pass<br><br>class Scanner:<br>    def scan_document(self):<br>        pass<br><br>class Fax:<br>    def fax_document(self):<br>        pass</pre><p>A basic printer can implement only the printing capability. A multifunction device can support all three.</p><p><strong>Benefit:</strong> Classes have fewer unnecessary dependencies and are easier to implement, test, and maintain.</p><p><strong>D — DIP: Dependency Inversion Principle</strong></p><p><strong>Principle:</strong> High-level business logic should depend on abstractions rather than directly on concrete implementations.</p><p><strong>Problem:</strong></p><pre>class EmailSender:<br>    def send(self, message):<br>        print(&quot;Sending email:&quot;, message)<br><br>class NotificationService:<br>    def __init__(self):<br>        self.sender = EmailSender()<br>    def notify(self, message):<br>        self.sender.send(message)</pre><p>NotificationService directly creates an EmailSender. Switching to SMS requires changing the notification service.</p><p><strong>Improved code:</strong></p><pre>class NotificationService:<br>    def __init__(self, sender):<br>        self.sender = sender<br><br>    def notify(self, message):<br>        self.sender.send(message)<br><br>class EmailSender:<br>    def send(self, message):<br>        print(&quot;Sending email:&quot;, message)<br><br>class SmsSender:<br>    def send(self, message):<br>        print(&quot;Sending SMS:&quot;, message)</pre><p><strong>Usage:</strong></p><pre>service = NotificationService(EmailSender())<br>service.notify(&quot;Bill processed&quot;)<br>service = NotificationService(SmsSender())<br>service.notify(&quot;Bill processed&quot;)</pre><p>Both senders provide the expected send() method, so the business logic does not need to change.</p><p><strong>Benefit:</strong> Implementations can be replaced more easily, and tests can inject mock senders instead of using real external services.</p><h4>5. SoC — Separation of Concerns</h4><p><strong>Principle:</strong> Separate distinct responsibilities into different modules or components.</p><p><strong>Problem:</strong></p><pre>def process_bill(bill):<br>    # Validate input<br>    # Calculate discounts<br>    # Save to database<br>    # Generate report<br>    pass</pre><p>One function mixes several unrelated tasks, making it difficult to test or modify a single part.</p><p><strong>Improved code:</strong></p><pre>def process_bill(bill):<br>    validate_bill(bill)<br>    calculate_discounts(bill)<br>    save_bill(bill)<br>    generate_report(bill)</pre><p>Each function handles a separate concern.</p><p><strong>Benefit:</strong> Individual steps can be tested and changed independently, and the overall workflow becomes easier to understand.</p><p><strong>Difference from SRP:</strong> SoC is the broader idea of separating concerns across a system. SRP applies that idea specifically to the responsibilities of a class or module.</p><h4>6. SLAP — Single Level of Abstraction Principle</h4><p><strong>Principle:</strong> Keep statements in a function at roughly the same level of detail. Move low-level implementation details into smaller functions.</p><p><strong>Problem:</strong></p><pre>def process_bill(bill):<br>    if bill[&quot;price&quot;] &lt; 0:<br>        raise ValueError(&quot;Invalid price&quot;)<br>discount = bill[&quot;price&quot;] * 0.30<br>    # Open database connection and execute SQL<br>    # Generate and send a report</pre><p>The function mixes business workflow, validation details, arithmetic, database operations, and reporting.</p><p><strong>Improved code:</strong></p><pre>def process_bill(bill):<br>    validate_bill(bill)<br>    apply_discount(bill)<br>    save_bill(bill)<br>    send_report(bill)</pre><p>Each step describes what happens rather than how every detail is implemented.</p><p><strong>Benefit:</strong> Readers can understand the workflow quickly and explore the implementation only when needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41418720a40a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete JavaScript Handbook: From Basics to Advanced Concepts]]></title>
            <link>https://javascript.plainenglish.io/the-complete-javascript-handbook-from-basics-to-advanced-concepts-68439d1a95fe?source=rss-8d2e3a58af0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68439d1a95fe</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Bashira Farhin]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 15:59:17 GMT</pubDate>
            <atom:updated>2026-08-08T17:16:57.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiU0dBYL3HD1t9gPEbTPgg.png" /></figure><h3>Introduction</h3><p>JavaScript is one of the most widely used programming languages in the world. Today, it powers everything from interactive websites and backend servers to desktop applications and even mobile apps.</p><p>However, JavaScript wasn’t originally designed to be this powerful.</p><p>In 1995, JavaScript was created by Brendan Eich in just <strong>10 days</strong> at Netscape. The language was initially developed to add interactivity to web pages, but over time it evolved into one of the most influential programming languages in software development.</p><p>This guide explains JavaScript from the ground up, focusing not only on <strong>what</strong> happens but also <strong>why</strong> it happens internally.</p><h3>Part 1 — JavaScript Fundamentals</h3><h3>What is ECMAScript?</h3><p>One of the biggest misconceptions among beginners is assuming JavaScript and ECMAScript are the same thing.</p><p>They are closely related, but they are <strong>not identical</strong>.</p><p><strong>ECMAScript</strong> is the official specification that defines how the JavaScript language should behave.</p><p><strong>JavaScript</strong> is an implementation of that specification.</p><p>Think of ECMAScript as the blueprint, while JavaScript is one implementation of that blueprint.</p><p>For example:</p><ul><li>ECMAScript defines that let should have block scope.</li><li>Chrome’s V8 engine implements that behavior.</li><li>Firefox’s SpiderMonkey implements the same behavior.</li><li>Safari’s JavaScriptCore also implements it.</li></ul><p>Every browser follows the ECMAScript specification so that JavaScript behaves consistently across platforms.</p><h3>What is JavaScript?</h3><p>JavaScript is a <strong>high-level</strong>, <strong>lightweight</strong>, <strong>dynamically typed</strong>, <strong>prototype-based</strong> programming language that supports <strong>first-class functions</strong>.</p><p>Unlike languages such as C++ or Java, JavaScript is executed by a JavaScript engine inside an existing runtime environment, such as a web browser or Node.js.</p><p>Modern JavaScript engines use <strong>Just-In-Time (JIT) compilation</strong>, meaning the code is compiled during execution for better performance.</p><h3>Why is JavaScript called a lightweight language?</h3><p>The term <strong>lightweight</strong> does <strong>not</strong> mean the language is weak or less capable.</p><p>Instead, it refers to the fact that JavaScript requires very little setup and relatively few system resources.</p><p>JavaScript is considered lightweight because:</p><ul><li>It does not require manual compilation before execution.</li><li>It runs directly inside a JavaScript engine provided by the browser or runtime.</li><li>It has a relatively small and simple syntax.</li><li>It is dynamically typed, reducing boilerplate code.</li><li>It is event-driven, making it ideal for interactive applications.</li><li>It consumes fewer resources compared to many traditionally compiled languages.</li></ul><p>For comparison:</p><pre>| Language   | Execution Model            | Requirements                 |<br>| ---------- | -------------------------- | ---------------------------- |<br>| JavaScript | JIT Compiled / Interpreted | Browser or Node.js runtime   |<br>| Java       | Ahead-of-Time Compiled     | JDK, JVM, compilation        |<br>| C++        | Ahead-of-Time Compiled     | Compiler, linker, executable |<br>| Python     | Interpreted                | Python Interpreter           |</pre><p>Why is JavaScript called a scripting language?</p><p>JavaScript is often referred to as a <strong>scripting language</strong>.</p><p>A scripting language is generally used to control or automate the behavior of an existing application rather than building an entire operating system or standalone application from scratch.</p><p>A <strong>script</strong> is simply a small program executed inside another program.</p><p>For JavaScript, that host program is usually:</p><ul><li>Chrome</li><li>Firefox</li><li>Edge</li><li>Safari</li><li>Node.js</li></ul><p>When JavaScript runs inside a browser, it controls the browser’s behavior rather than creating the browser itself.</p><p>For example:</p><ul><li>Handling button clicks</li><li>Updating the DOM</li><li>Changing CSS styles</li><li>Making API requests</li><li>Validating forms</li><li>Animating UI components</li></ul><p>JavaScript manipulates existing HTML elements instead of generating the browser’s rendering engine or DOM implementation</p><p>Why JavaScript is considered a scripting language?</p><p>JavaScript satisfies the traditional definition of a scripting language because:</p><ul><li>It executes inside another application (browser or Node.js).</li><li>It is embedded into HTML to make pages interactive.</li><li>It primarily controls existing objects like the DOM, CSS, and browser APIs.</li><li>It originally executed line-by-line without producing standalone machine code.</li></ul><p>Although modern JavaScript engines now use JIT compilation, the language is still historically and conceptually categorized as a scripting language.</p><h3>How JavaScript Executes Inside the Browser</h3><p>When a browser encounters JavaScript, it does <strong>not</strong> understand the source code directly. Instead, it passes the code to its JavaScript engine.</p><p>Different browsers have different engines:</p><pre>| Browser | JavaScript Engine |<br>| ------- | ----------------- |<br>| Chrome  | V8                |<br>| Edge    | V8                |<br>| Firefox | SpiderMonkey      |<br>| Safari  | JavaScriptCore    |</pre><p>The engine then converts your JavaScript into machine code that the CPU can execute.</p><h3>Evolution of JavaScript Execution</h3><p>Originally, JavaScript engines worked purely as interpreters.</p><p>The process was simple:</p><ol><li>Read one line.</li><li>Interpret it.</li><li>Execute it.</li><li>Move to the next line.</li></ol><p>This approach was easy but relatively slow because every execution required interpretation.</p><p>Modern browsers use <strong>Just-In-Time (JIT) compilation</strong>.</p><p>Instead of interpreting every line repeatedly, the engine identifies frequently executed code and compiles it into optimized machine code during runtime.</p><p>This dramatically improves performance while maintaining fast startup times.</p><h3>High-Level JavaScript Execution Pipeline</h3><p>When a browser loads a JavaScript file, the engine performs several internal steps.</p><pre>JavaScript Source<br>        │<br>        ▼<br> Tokenization (Lexing)<br>        │<br>        ▼<br>      Parsing<br>        │<br>        ▼<br> Abstract Syntax Tree (AST)<br>        │<br>        ▼<br> Bytecode Generation<br>        │<br>        ▼<br> Ignition Interpreter (V8)<br>        │<br>        ▼<br> Runtime Profiling<br>        │<br>        ▼<br> TurboFan Optimizing Compiler<br>        │<br>        ▼<br> Optimized Machine Code<br>        │<br>        ▼<br> CPU Execution</pre><p>Let’s understand each stage.</p><h3>1. Fetch Source</h3><p>The browser downloads the JavaScript file or reads inline scripts.</p><h3>2. Lexical Analysis (Tokenization)</h3><p>The source code is broken into tokens.</p><p>For example,</p><pre>let age = 25;</pre><p>becomes tokens similar to:</p><pre>let identifier(age) = number(25);</pre><h3>3. Parsing</h3><p>The parser verifies that the syntax is valid. If everything is correct, it creates an <strong>Abstract Syntax Tree (AST)</strong>. The AST is a tree representation of your program that describes its structure rather than its text.</p><h3>4. Bytecode Generation</h3><p>Modern engines typically convert the AST into bytecode. Bytecode is an intermediate representation that is faster to interpret than repeatedly traversing the AST.</p><h3>5. Ignition Interpreter</h3><p>In Chrome’s V8 engine, the <strong>Ignition</strong> interpreter begins executing the generated bytecode. This allows JavaScript to start running almost immediately without waiting for expensive optimizations.</p><h3>6. Runtime Profiling</h3><p>While executing your code, the engine gathers runtime information such as:</p><ul><li>Which functions execute most frequently</li><li>Data types used</li><li>Function call counts</li><li>Property access patterns</li></ul><p>Frequently executed functions are called <strong>hot functions</strong>.</p><h3>7. TurboFan Optimization</h3><p>When the engine identifies hot code, it sends it to <strong>TurboFan</strong>, V8’s optimizing compiler. TurboFan generates highly optimized machine code using the profiling information collected during execution.</p><h3>8. Machine Code Execution</h3><p>Future executions of the optimized function bypass the interpreter entirely and execute directly as machine code. This provides a significant performance improvement.</p><h3>9. Deoptimization</h3><p>Sometimes the optimizer makes assumptions.</p><p>For example:</p><pre>let x = 10;</pre><p>The engine may assume x is always a number.</p><p>Later:</p><pre>x = &quot;Hello&quot;;</pre><p>That assumption becomes invalid.</p><p>The engine discards the optimized code and falls back to the interpreter before potentially recompiling the function using safer assumptions.</p><p>This process is known as <strong>deoptimization</strong>.</p><h3>10. Garbage Collection</h3><p>JavaScript automatically manages memory.</p><p>Objects that are no longer reachable are periodically removed from memory by the <strong>garbage collector</strong>, freeing heap space for future allocations.</p><h3>Just-In-Time Compilation</h3><p>JavaScript is commonly described as a <strong>Just-In-Time (JIT) compiled language</strong>.</p><p>Unlike Ahead-of-Time (AOT) compiled languages such as C++ or Java, JavaScript performs compilation <strong>during execution</strong>.</p><p>Instead of compiling the entire program before it runs, the engine compiles only the portions of code that benefit from optimization.</p><p>This approach provides an excellent balance between startup speed and runtime performance.</p><h3><strong>Part 2 — Loading JavaScript in the Browser</strong></h3><p>Writing JavaScript is only one part of the story. Before your code can execute, the browser must know <strong>when</strong> and <strong>how</strong> to load it.</p><p>Where you place the &lt;script&gt; tag directly affects page rendering, execution order, and application performance.</p><p>Understanding this process is essential for building fast and reliable web applications.</p><h3>Ways to Include JavaScript</h3><p>JavaScript can be added to an HTML page in three primary ways:</p><ol><li>Inside the &lt;head&gt; section</li><li>Inside the &lt;body&gt; section</li><li>Using an external JavaScript file</li></ol><p>Each approach has its own advantages and trade-offs.</p><ol><li>Placing JavaScript Inside the &lt;head&gt;</li></ol><pre>&lt;head&gt;<br>    &lt;script&gt;<br>        alert(&quot;This runs from the head section&quot;);<br>    &lt;/script&gt;<br>&lt;/head&gt;</pre><p>When the browser encounters a normal &lt;script&gt; tag inside the &lt;head&gt;, it immediately pauses HTML parsing.</p><p>The browser performs the following sequence:</p><ol><li>Stop parsing HTML.</li><li>Download the script (if external).</li><li>Execute the script.</li><li>Resume parsing the remaining HTML.</li></ol><h3>Advantages</h3><ul><li>Keeps initialization scripts together.</li><li>Useful for analytics scripts.</li><li>Useful for configuration code.</li><li>Suitable when certain libraries must load before anything else.</li></ul><h3>Disadvantages</h3><p>Since HTML parsing stops until the script finishes executing, the user may experience a slower page load.</p><p>Another important issue is that DOM elements appearing later in the document have not yet been created.</p><p>For example,</p><pre>&lt;head&gt;<br>    &lt;script&gt;<br>        document.querySelector(&quot;button&quot;).click();<br>    &lt;/script&gt;<br>&lt;/head&gt;</pre><p>This produces an error because the &lt;button&gt; element does not yet exist.</p><p>In such cases, developers either:</p><ul><li>wait for the DOMContentLoaded event, or</li><li>use the defer attribute.</li></ul><h3>2. Placing JavaScript Inside the &lt;body&gt;</h3><pre>&lt;body&gt;<br><br>&lt;h1&gt;Hello World&lt;/h1&gt;<br><br>&lt;script&gt;<br>document.querySelector(&quot;h1&quot;).style.color = &quot;blue&quot;;<br>&lt;/script&gt;<br><br>&lt;/body&gt;</pre><p>Here, the browser has already parsed the &lt;h1&gt; before reaching the script.</p><p>Therefore,</p><pre>document.querySelector(&quot;h1&quot;)</pre><p>returns the actual DOM element successfully.</p><h3>Advantages</h3><ul><li>Safe for DOM manipulation.</li><li>HTML is rendered before JavaScript executes.</li><li>Faster perceived page load than placing scripts in the &lt;head&gt;.</li></ul><h3>Disadvantages</h3><ul><li>Mixing HTML and JavaScript reduces maintainability.</li><li>Large inline scripts make HTML difficult to read.</li><li>Reusing the same script across multiple pages becomes difficult.</li></ul><h3>3. Using an External JavaScript File</h3><pre>&lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;</pre><p>This is the preferred approach for almost every real-world project.</p><p>Instead of writing JavaScript directly inside HTML, all code is placed in separate .js files.</p><h3>Advantages</h3><ul><li>Cleaner HTML.</li><li>Better organization.</li><li>Easier maintenance.</li><li>Easier collaboration.</li><li>Browser caching improves subsequent page loads.</li><li>The same file can be reused across multiple pages.</li></ul><h3>Disadvantages</h3><p>The browser must make an additional HTTP request to download the JavaScript file.</p><p>If the file path is incorrect or the server cannot provide the file, the script will not execute.</p><p>For production applications, however, the benefits greatly outweigh this small cost.</p><h3>What Happens When the Browser Encounters a &lt;script&gt; Tag?</h3><p>Suppose the browser is parsing this document:</p><pre>&lt;html&gt;<br>&lt;body&gt;<br><br>&lt;h1&gt;Hello&lt;/h1&gt;<br><br>&lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br><br>&lt;p&gt;Welcome&lt;/p&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The browser works approximately like this:</p><pre>Parse HTML<br><br>↓<br><br>&lt;h1&gt; created<br><br>↓<br><br>&lt;script&gt; encountered<br><br>↓<br><br>Stop HTML parsing<br><br>↓<br><br>Download app.js<br><br>↓<br><br>Execute app.js<br><br>↓<br><br>Resume HTML parsing<br><br>↓<br><br>&lt;p&gt; created</pre><p>This blocking behavior is the reason developers use <strong>async</strong> and <strong>defer</strong>.</p><h3>Normal Script Loading</h3><p>A normal script behaves synchronously.</p><pre>HTML Parsing<br>      │<br>      ▼<br>Script Found<br>      │<br>      ▼<br>Parsing Stops<br>      │<br>      ▼<br>Download Script<br>      │<br>      ▼<br>Execute Script<br>      │<br>      ▼<br>Resume HTML Parsing</pre><p>While this guarantees execution order, it also blocks rendering.</p><h3>The async Attribute</h3><p>The async attribute allows the browser to continue parsing HTML while downloading the JavaScript file.</p><pre>&lt;script async src=&quot;app.js&quot;&gt;&lt;/script&gt;</pre><p>The sequence becomes:</p><pre>HTML Parsing<br>      │<br>      ├───────────────┐<br>      │               │<br>Continue Parsing   Download Script<br>      │               │<br>      └──────┬────────┘<br>             │<br>      Pause Parsing<br>             │<br>      Execute Script<br>             │<br>      Resume Parsing</pre><p>The browser only pauses parsing <strong>when the downloaded script is ready to execute</strong>.</p><h3>Advantages of async</h3><ul><li>Faster page rendering.</li><li>JavaScript downloads in parallel with HTML.</li><li>Excellent for independent scripts.</li></ul><p>Examples include:</p><ul><li>Analytics</li><li>Advertisements</li><li>Tracking pixels</li><li>Monitoring scripts</li></ul><h3>Disadvantages of async</h3><p>Execution order is <strong>not guaranteed</strong>.</p><p>Imagine:</p><pre>&lt;script async src=&quot;script1.js&quot;&gt;&lt;/script&gt;<br>&lt;script async src=&quot;script2.js&quot;&gt;&lt;/script&gt;</pre><p>Suppose script2.js contains</p><pre>console.log(window.count + 5);</pre><p>while script1.js contains</p><pre>window.count = 10;</pre><p>If script2.js finishes downloading first, it executes before script1.js.</p><p>Now,</p><pre>window.count</pre><p>is still undefined. This can break the application.</p><p>Therefore, async should only be used for scripts that are completely independent.</p><h3>The defer Attribute</h3><p>The defer attribute solves this problem.</p><pre>&lt;script defer src=&quot;script1.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;script2.js&quot;&gt;&lt;/script&gt;</pre><p>With defer, the browser behaves differently.</p><pre>HTML Parsing<br>      │<br>      ├───────────────┐<br>      │               │<br>Continue Parsing   Download Scripts<br>      │               │<br>      ▼               ▼<br>HTML Finished Parsing<br>      │<br>      ▼<br>Execute Script 1<br>      │<br>      ▼<br>Execute Script 2</pre><p>Notice two important differences.</p><h3>HTML parsing never stops.</h3><p>The page continues rendering while scripts download.</p><h3>Execution order is preserved.</h3><p>Even if script2.js downloads before script1.js, the browser still executes them in document order.</p><h3>Advantages of defer</h3><ul><li>HTML parsing never blocks.</li><li>DOM is completely built before execution.</li><li>Script order is preserved.</li><li>Perfect for application code.</li></ul><p>For modern web applications, defer is usually the best choice.</p><p>Async vs Defer</p><pre>| Feature                   | Normal        | Async                 | Defer                 |<br>| ------------------------- | ------------- | --------------------- | --------------------- |<br>| Blocks HTML parsing       | Yes           | Only during execution | No                    |<br>| Downloads in parallel     | No            | Yes                   | Yes                   |<br>| Maintains execution order | Yes           | No                    | Yes                   |<br>| Waits until DOM is built  | No            | No                    | Yes                   |<br>| Best for                  | Small scripts | Analytics             | Main application code |</pre><p>As a general rule:</p><ul><li>Use <strong>normal scripts</strong> only when absolutely necessary.</li><li>Use <strong>async</strong> for independent third-party scripts.</li><li>Use <strong>defer</strong> for your application’s JavaScript.</li></ul><h3>The &lt;noscript&gt; Tag</h3><p>Sometimes JavaScript may be disabled in the user’s browser.</p><p>In such cases, the browser ignores every &lt;script&gt; tag.</p><p>To provide fallback content, HTML offers the &lt;noscript&gt; element.</p><pre>&lt;noscript&gt;<br>Please enable JavaScript to use this application.<br>&lt;/noscript&gt;</pre><p>Everything inside &lt;noscript&gt; is displayed <strong>only if JavaScript is disabled or unsupported</strong>. This is commonly used to display warning messages or alternative content for users without JavaScript.</p><h3>Part 3 — Variables, Scope, Hoisting, and the Temporal Dead Zone</h3><p>Variables are fundamental to every programming language. They allow us to store information that can later be read or modified during program execution. JavaScript provides three ways to declare variables:</p><ul><li>var</li><li>let</li><li>const</li></ul><h3>Declaring Variables</h3><h3>Using var</h3><pre>var age = 25;</pre><p>Variables declared with var can be:</p><ul><li>Redeclared</li><li>Reassigned</li><li>Function scoped</li></ul><p>Example:</p><pre>var age = 25;<br>var age = 30;<br>console.log(age);</pre><p>Output:</p><pre>30</pre><p>No error occurs because redeclaration is allowed.</p><h3>Using let</h3><pre>let age = 25;</pre><p>A let variable:</p><ul><li>Cannot be redeclared in the same scope</li><li>Can be reassigned</li><li>Is block scoped</li></ul><p>Example:</p><pre>let age = 25;<br>age = 30;<br>console.log(age);</pre><p>Output:</p><pre>30</pre><p>However,</p><pre>let age = 25;<br>let age = 30;</pre><p>throws</p><pre>SyntaxError<br>Identifier &#39;age&#39; has already been declared</pre><p>Using const</p><pre>const age = 25;</pre><p>A const variable:</p><ul><li>Cannot be redeclared</li><li>Cannot be reassigned</li><li>Is block scoped</li></ul><p>Example:</p><pre>const PI = 3.14159;</pre><p>Attempting</p><pre>PI = 1</pre><p>produces</p><pre>TypeError<br>Assignment to constant variable.</pre><p>Quick Comparison</p><pre>| Feature                | var      | let   | const |<br>| ---------------------- | -------- | ----- | ----- |<br>| Redeclaration          | Yes      | No    | No    |<br>| Reassignment           | Yes      | Yes   | No    |<br>| Scope                  | Function | Block | Block |<br>| Hoisted                | Yes      | Yes   | Yes   |<br>| Temporal Dead Zone     | No       | Yes   | Yes   |<br>| Added to global object | Yes      | No    | No    |</pre><h3>Variable Naming Rules</h3><p>A variable name:</p><ul><li>Must begin with a letter</li><li>May begin with _</li><li>May begin with $</li><li>Cannot begin with a number</li><li>Cannot contain spaces</li><li>Cannot use reserved keywords</li></ul><p>Valid examples:</p><pre>let age;<br>let firstName;<br>let _count;<br>let $price;</pre><p>Invalid examples:</p><pre>let 1age;<br>let first name;<br>let class;</pre><h3>Understanding Scope</h3><p>Scope determines <strong>where a variable is accessible</strong>.</p><p>JavaScript has three primary kinds of scope.</p><ul><li>Global Scope</li><li>Function Scope</li><li>Block Scope</li><li>Module Scope</li></ul><h3>Global Scope</h3><p>A variable declared outside every function or block belongs to the global scope.</p><pre>let language = &quot;JavaScript&quot;;<br>function print() {<br>    console.log(language);<br>}<br>print();</pre><p>Output</p><pre>JavaScript</pre><p>Since language is global, every function can access it.</p><h3>Function Scope</h3><p>Variables declared using var are function scoped.</p><pre>function demo() {<br>var x = 10;<br>    console.log(x);<br>}<br>demo();</pre><p>Output</p><pre>10</pre><p>Outside the function,</p><pre>console.log(x);</pre><p>produces</p><pre>ReferenceError</pre><p>because x belongs only to that function.</p><h3>Block Scope</h3><p>Blocks are enclosed using curly braces.</p><pre>{<br>}</pre><p>Variables declared using let and const belong only to that block.</p><p>Example:</p><pre>{<br>let age = 20;<br>}<br>console.log(age);</pre><p>Output</p><pre>ReferenceError</pre><p>The variable ceases to exist once execution leaves the block</p><h3>Module Scope</h3><p>Variables declared at the top level of an <strong>ES module</strong> are <strong>module scoped</strong>. They are accessible anywhere within that module but are <strong>not added to the global object</strong> and cannot be accessed from other modules unless explicitly exported.</p><p>Example:</p><p><strong>math.js</strong></p><pre>const PI = 3.14159;<br>function area(radius) {<br>  return PI * radius * radius;<br>}<br>console.log(area(2));</pre><p><strong>Output</strong></p><pre>12.56636</pre><p>However, trying to access PI from another module without exporting it results in an error.</p><pre>// app.js<br>console.log(PI);</pre><p><strong>Output</strong></p><pre>ReferenceError</pre><p>To make a module-scoped variable available to other modules, it must be exported.</p><pre>// math.js<br>export const PI = 3.14159;<br><br>// app.js<br>import { PI } from &quot;./math.js&quot;;<br>console.log(PI);</pre><p>Module scope helps prevent accidental global variables and keeps code organized by exposing only what needs to be shared.</p><h3>Function Scope vs Block Scope</h3><p>Consider this example.</p><pre>if (true) {<br><br>    var a = 10;<br><br>}<br><br>console.log(a);</pre><p>Output</p><pre>10</pre><p>The if statement does <strong>not</strong> create a function.</p><p>Since var ignores blocks, a remains accessible.</p><p>Now compare it with let.</p><pre>if (true) {<br><br>    let a = 10;<br><br>}<br><br>console.log(a);</pre><p>Output</p><pre>ReferenceError</pre><p>Because let is block scoped.</p><h3>A Common Interview Question</h3><pre>for (var i = 0; i &lt; 5; i++) {<br><br>}<br><br>console.log(i);</pre><p>Output</p><pre>5</pre><p>Now,</p><pre>for (let i = 0; i &lt; 5; i++) {<br>}<br>console.log(i);</pre><p>Output</p><pre>ReferenceError</pre><p>The variable declared using let exists only inside the loop block</p><h3>How the JavaScript Engine Executes Your Code</h3><p>Most developers imagine that JavaScript simply executes code line by line.</p><p>In reality, that’s only half of the story.</p><p>Before execution begins, JavaScript performs an important preparation step.</p><p>Every execution context consists of <strong>two phases</strong>:</p><ol><li>Creation Phase</li><li>Execution Phase</li></ol><p>Understanding these two phases explains <strong>hoisting</strong>, the <strong>Temporal Dead Zone</strong>, and many seemingly strange JavaScript behaviors.</p><h3>The Creation Phase</h3><p>Before executing a single line of your program, JavaScript scans the entire scope. During this phase, memory is allocated for variables and functions. No assignments occur yet.</p><p>Consider this code.</p><pre>console.log(x);<br>var x = 10;</pre><p>Before execution starts, JavaScript has already allocated memory for x. Internally, it resembles:</p><pre>Global Memory<br>x → undefined</pre><p>Notice that the value is <strong>undefined</strong>, not 10.</p><p>Assignments happen only during the execution phase.</p><h3>The Execution Phase</h3><p>Now JavaScript begins executing the code line by line.</p><pre>console.log(x);</pre><p>prints</p><pre>undefined</pre><p>because x already exists in memory.</p><p>Next,</p><pre>var x = 10;</pre><p>updates memory. Now memory becomes</p><pre>x → 10</pre><h3>Hoisting</h3><p>This behavior is known as <strong>hoisting</strong>.</p><p>Hoisting means:</p><blockquote><em>During the creation phase, JavaScript allocates memory for declarations before execution begins.</em></blockquote><p>A common misconception is that variables “move to the top.”</p><p>They do not.</p><p>Nothing is physically moved.</p><p>Only memory allocation happens before execution.</p><h3>Function Hoisting</h3><p>Functions are hoisted differently.</p><p>Consider:</p><pre>sayHello();<br><br>function sayHello() {<br><br>    console.log(&quot;Hello&quot;);<br><br>}</pre><p>Output</p><pre>Hello</pre><p>During the creation phase, instead of</p><pre>sayHello → undefined</pre><p>JavaScript stores the <strong>entire function definition</strong>.</p><p>So memory already contains</p><pre>sayHello →<br><br>function sayHello(){<br><br>...<br>}</pre><p>Therefore the function can be called before its declaration.</p><h3>Function Expressions Behave Differently</h3><pre>hello();<br><br>var hello = function(){<br><br>    console.log(&quot;Hello&quot;);<br><br>}</pre><p>Output</p><pre>TypeError<br>hello is not a function</pre><p>Why?</p><p>Because only the variable is hoisted. Memory initially contains</p><pre>hello → undefined</pre><p>During execution, JavaScript tries</p><pre>undefined();</pre><p>which naturally throws an error.</p><h3>Memory Visualization</h3><p>Consider</p><pre>var a = 10;<br><br>let b = 20;<br><br>const c = 30;</pre><p>During creation, JavaScript allocates memory differently.</p><pre>Global Execution Context<br><br>-------------------------<br><br>Global Memory<br><br>a → undefined<br><br>-------------------------<br><br>Lexical Environment<br><br>b → &lt;uninitialized&gt;<br><br>c → &lt;uninitialized&gt;</pre><p>Notice something interesting.</p><p>var lives in a different environment than let and const.</p><p>This distinction leads us to one of JavaScript’s most misunderstood concepts: the <strong>Temporal Dead Zone (TDZ)</strong>.</p><h3>Part 4 — The Temporal Dead Zone (TDZ)</h3><p>If you’ve been learning JavaScript for a while, you’ve probably seen this code:</p><pre>console.log(a);<br>var a = 10;</pre><p>Most beginners expect an error. Instead, JavaScript prints:</p><pre>undefined</pre><p>Now consider this example:</p><pre>console.log(a);<br>let a = 10;</pre><p>This time the browser throws:</p><pre>ReferenceError:<br>Cannot access &#39;a&#39; before initialization</pre><p>The obvious question is:</p><blockquote><em>If both </em><em>var and </em><em>let are hoisted, why does one print </em><em>undefined while the other throws an error?</em></blockquote><p>The answer lies in one of JavaScript&#39;s most important concepts:</p><p><strong>The Temporal Dead Zone (TDZ).</strong></p><h3>First, Let’s Clear Up a Common Myth</h3><p>Many developers believe that:</p><blockquote><em>“let and </em><em>const are not hoisted.&quot;</em></blockquote><p>This is <strong>incorrect</strong>.</p><p>In reality,</p><ul><li>var is hoisted.</li><li>let is hoisted.</li><li>const is hoisted.</li></ul><p>The difference is <strong>not whether they are hoisted</strong>, but <strong>how they are initialized during the creation phase</strong>.</p><h3>Revisiting the Creation Phase</h3><p>Before your code starts executing, JavaScript creates the execution context.</p><p>During this phase:</p><ul><li>Memory is allocated for variables.</li><li>Functions are stored in memory.</li><li>The lexical environment is prepared.</li></ul><p>Consider the following code:</p><pre>var x = 10;<br><br>let y = 20;<br><br>const z = 30;</pre><p>Before execution begins, memory looks conceptually like this:</p><pre>Global Execution Context<br><br>Memory<br><br>x → undefined<br><br>Lexical Environment<br><br>y → &lt;uninitialized&gt;<br><br>z → &lt;uninitialized&gt;</pre><p>Notice the difference.</p><p>var is immediately initialized with undefined. let and const are allocated memory, but they remain <strong>uninitialized</strong>. This “uninitialized” state is the key to understanding the TDZ.</p><h3>What Exactly Is the Temporal Dead Zone?</h3><p>The <strong>Temporal Dead Zone</strong> is the period between:</p><ul><li>when a variable is created during the creation phase, and</li><li>when its declaration is executed during the execution phase.</li></ul><p>During this period, the variable exists in memory but cannot be accessed.</p><p>That’s why this code fails:</p><pre>console.log(score);<br>let score = 100;</pre><p>Although score already exists in memory, it is still in the Temporal Dead Zone. Trying to access it produces:</p><pre>ReferenceError:<br>Cannot access &#39;score&#39; before initialization</pre><h3>Why Doesn’t var Have a TDZ?</h3><p>Consider this code:</p><pre>console.log(age);<br>var age = 25;</pre><p>During the creation phase:</p><pre>age → undefined</pre><p>Since age is already initialized with undefined, JavaScript has something valid to return.</p><p>Therefore,</p><pre>console.log(age);</pre><p>prints</p><pre>undefined</pre><p>instead of throwing an error.</p><h3>Visualizing the Timeline</h3><p>Imagine the execution of this program:</p><pre>console.log(city);<br>let city = &quot;Delhi&quot;;</pre><p>Internally, the timeline looks something like this:</p><pre>Creation Phase<br>────────────────────────────<br><br>city exists<br><br>↓<br><br>city = &lt;uninitialized&gt;<br><br>────────────────────────────<br><br>Execution Phase<br><br>↓<br><br>console.log(city)<br><br>↓<br><br>ReferenceError<br><br>↓<br><br>let city = &quot;Delhi&quot;<br><br>↓<br><br>city = &quot;Delhi&quot;<br><br>↓<br><br>TDZ Ends</pre><p>The variable exists throughout the program, but it cannot be used until JavaScript executes its declaration.</p><h3>Does const Also Have a TDZ?</h3><p>Absolutely.</p><pre>console.log(PI);<br>const PI = 3.14;</pre><p>produces:</p><pre>ReferenceError</pre><p>for exactly the same reason. The only additional rule with const is that it <strong>must</strong> be initialized at the time of declaration.</p><p>This is invalid:</p><pre>const PI;</pre><p>because JavaScript has no value to assign when initialization finally occurs.</p><h3>Why Was the TDZ Introduced?</h3><p>Imagine if let behaved exactly like var.</p><pre>let total;<br>console.log(total);<br>total = calculatePrice();</pre><p>If JavaScript silently returned undefined, bugs like this could remain hidden for hours. Instead, JavaScript immediately reports the mistake:</p><blockquote><em>“You’re trying to use a variable before it’s ready.”</em></blockquote><p>The TDZ exists to make your code safer and easier to debug.</p><h3>var and the Global Object</h3><p>Another important distinction between var, let, and const appears when variables are declared in the global scope.</p><p>Consider this example in a browser:</p><pre>var language = &quot;JavaScript&quot;;<br>console.log(window.language);</pre><p>Output:</p><pre>JavaScript</pre><p>Why?</p><p>Because globally declared var variables become properties of the browser&#39;s global object (window). Internally, this is roughly equivalent to:</p><pre>window.language = &quot;JavaScript&quot;;</pre><p>Now compare it with let:</p><pre>let framework = &quot;React&quot;;<br>console.log(window.framework);</pre><p>Output:</p><pre>undefined</pre><p>The same happens with const.</p><pre>const version = &quot;ES2025&quot;;<br>console.log(window.version);</pre><p>Output:</p><pre>undefined</pre><p>Unlike var, let and const create bindings in the global lexical environment, <strong>not</strong> properties on the global object.</p><p>This design avoids accidental pollution of the global namespace.</p><h3>Understanding Shadowing</h3><p>Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope. The inner variable temporarily “shadows” or hides the outer one.</p><p>Example:</p><pre>let message = &quot;Outer&quot;;<br>{<br>    let message = &quot;Inner&quot;;<br>    console.log(message);<br>}<br>console.log(message);</pre><p>Output:</p><pre>Inner<br>Outer</pre><p>Inside the block, JavaScript always uses the nearest declaration. Once execution leaves the block, the outer variable becomes visible again.</p><h3>var Shadowing</h3><p>Since var is function scoped rather than block scoped, shadowing behaves differently.</p><pre>var count = 10;<br><br>{<br>    var count = 20;<br>}<br><br>console.log(count);</pre><p>Output:</p><pre>20</pre><p>The block does not create a new scope for var.</p><p>Instead, both declarations refer to the same variable.</p><p>This is one of the reasons modern JavaScript recommends avoiding var in favor of let and const.</p><h3>Illegal Shadowing</h3><p>JavaScript also prevents certain combinations of declarations because they would create ambiguous behavior.</p><p>Consider this example:</p><pre>let value = 10;<br>{<br>    var value = 20;<br>}</pre><p>This throws:</p><pre>SyntaxError:<br>Identifier &#39;value&#39; has already been declared</pre><p>Why?</p><p>The var declaration is function scoped and attempts to create another value in the same scope where a let binding already exists.</p><p>However, the reverse is perfectly valid because let creates a new block scope:</p><pre>var value = 10;<br>{<br>    let value = 20;<br>}<br>console.log(value);</pre><p>Output:</p><pre>10</pre><p>Here, the inner let variable exists only inside the block and simply shadows the outer var without causing a conflict.</p><h3>Part 5 — Primitive vs Reference Types</h3><h3>JavaScript Data Types</h3><p>JavaScript data types are divided into two categories:</p><ol><li>Primitive Data Types</li><li>Reference (Non-Primitive) Data Types</li></ol><h3>Primitive Data Types</h3><p>Primitive values are immutable and represent a single value.</p><p>JavaScript has seven primitive data types:</p><ul><li>string</li><li>number</li><li>bigint</li><li>boolean</li><li>undefined</li><li>symbol</li><li>null</li></ul><p>Example:</p><pre>let name = &quot;Alice&quot;;<br>let age = 25;<br>let isLoggedIn = true;<br>let score;<br>let salary = 12345678901234567890n;<br>let id = Symbol(&quot;id&quot;);<br>let user = null;</pre><p>Each variable stores its own value independently.</p><h3>Characteristics of Primitive Values</h3><p>Primitive values have several important characteristics:</p><ul><li>They store a single value.</li><li>They are immutable.</li><li>They are copied by value.</li><li>They are compared by value.</li><li>They are usually stored directly in the stack (conceptually).</li></ul><p>The word <strong>immutable</strong> means that once a primitive value is created, it cannot be changed.</p><p>For example,</p><pre>let language = &quot;JavaScript&quot;;<br>language = &quot;TypeScript&quot;;</pre><p>It may appear that the string &quot;JavaScript&quot; was modified, but that&#39;s not what actually happened.</p><p>Instead:</p><ol><li>A new string &quot;TypeScript&quot; was created.</li><li>The variable language now points to this new value.</li><li>The original string remains unchanged until it is eventually removed by the garbage collector if nothing references it.</li></ol><h3>Reference (Non-Primitive) Data Types</h3><p>Reference values can contain multiple values or complex structures.</p><p>Examples include:</p><ul><li>Objects</li><li>Arrays</li><li>Functions</li><li>Dates</li><li>Maps</li><li>Sets</li><li>Regular Expressions</li></ul><p>Example:</p><pre>const person = {<br>    name: &quot;Alice&quot;,<br>    age: 25<br>};<br>const numbers = [1, 2, 3];<br>function greet() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><p>Unlike primitives, these values are mutable.</p><h3>Why Are They Called Reference Types?</h3><p>Suppose we create an object.</p><pre>const person = {<br>    name: &quot;John&quot;<br>};</pre><p>The object itself is <strong>not</strong> stored directly inside the variable.</p><p>Instead, JavaScript creates the object somewhere in memory and stores only a reference (or memory address) inside the variable.</p><p>Conceptually, memory looks like this:</p><pre>Stack<br><br>person<br> │<br> │<br> ▼<br>Heap Address: 0x001<br><br>------------------------<br><br>Heap<br><br>0x001<br><br>{<br><br>name: &quot;John&quot;<br><br>}</pre><p>The variable person contains a reference to the object, not the object itself.</p><h3>Understanding Stack and Heap Memory</h3><p>Although JavaScript engines have sophisticated memory management strategies, it’s useful to think of memory in two conceptual areas:</p><ul><li>Stack Memory</li><li>Heap Memory</li></ul><p>This mental model helps explain why primitives and objects behave differently.</p><h3>Stack Memory</h3><p>The stack is used for:</p><ul><li>Primitive values</li><li>Function calls</li><li>Local execution contexts</li></ul><p>Stack memory is:</p><ul><li>Fast</li><li>Organized</li><li>Automatically managed</li><li>Short-lived</li></ul><p>Example:</p><pre>let age = 25;<br>let active = true;</pre><p>Conceptually:</p><pre>Stack<br>age → 25<br>active → true</pre><p>Each variable directly stores its value.</p><h3>Heap Memory</h3><p>The heap is used for:</p><ul><li>Objects</li><li>Arrays</li><li>Functions</li><li>Complex data structures</li></ul><p>Heap memory is:</p><ul><li>Larger</li><li>Dynamic</li><li>Slightly slower than the stack</li><li>Managed by the garbage collector</li></ul><p>Objects are allocated in the heap because their size is not known in advance and can change during execution.</p><h3>Copying Primitive Values</h3><p>Let’s see what happens when we copy a primitive value.</p><pre>let a = 10;<br><br>let b = a;<br><br>b = 20;</pre><p>Many beginners assume that changing b will also change a.</p><p>Let’s verify.</p><pre>console.log(a);<br>console.log(b);</pre><p>Output:</p><pre>10<br><br>20</pre><p>Why?</p><p>Because primitive values are copied <strong>by value</strong>.</p><p>Conceptually:</p><pre>Stack<br><br>a → 10<br><br>b → 10</pre><p>After:</p><pre>b = 20;</pre><p>Memory becomes:</p><pre>Stack<br><br>a → 10<br><br>b → 20</pre><p>The variables are completely independent.</p><h3>Copying Objects</h3><p>Now consider an object.</p><pre>const user1 = {<br>name: &quot;John&quot;<br>};<br>const user2 = user1;</pre><p>Most beginners expect JavaScript to create a second object.</p><p>It doesn’t.</p><p>Instead:</p><pre>Stack<br><br>user1 ───────┐<br><br>             │<br><br>user2 ───────┘<br><br>             │<br><br>             ▼<br><br>Heap<br><br>{<br><br>name: &quot;John&quot;<br><br>}</pre><p>Both variables point to the exact same object.</p><h3>Modifying One Reference</h3><p>Now suppose we write:</p><pre>user2.name = &quot;Alice&quot;;</pre><p>What will happen?</p><pre>console.log(user1.name);</pre><p>Output:</p><pre>Alice</pre><p>This surprises many developers the first time they encounter it.</p><p>Nothing magical happened.</p><p>There was only <strong>one object</strong> in memory.</p><p>Both variables simply referenced it.</p><h3>Comparing Primitive Values</h3><p>Primitive values are compared based on their actual contents.</p><pre>let x = 10;<br><br>let y = 10;<br><br>console.log(x === y</pre><p>Output:</p><pre>true</pre><p>The values themselves are identical.</p><h3>Comparing Objects</h3><p>Objects behave differently.</p><pre>const a = {<br><br>    name: &quot;John&quot;<br><br>};<br><br>const b = {<br><br>    name: &quot;John&quot;<br><br>};<br><br>console.log(a === b);</pre><p>Output:</p><pre>false</pre><p>Although both objects contain identical data, they occupy different locations in memory.</p><p>Conceptually:</p><pre>Stack<br><br>a ─────► Heap Address 101<br><br>b ─────► Heap Address 205</pre><p>Different addresses mean different objects.</p><p>Therefore:</p><pre>a === b</pre><p>returns false.</p><h3>When Object Comparison Returns true</h3><p>Consider this example.</p><pre>const a = {<br><br>    name: &quot;John&quot;<br><br>};<br><br>const b = a;<br><br>console.log(a === b);</pre><p>Output:</p><pre>true</pre><p>Both variables point to the same object.</p><p>JavaScript compares references, not object contents.</p><h3>A Common Interview Question</h3><p>What will this print?</p><pre>const arr1 = [1, 2, 3];<br>const arr2 = [1, 2, 3];<br>console.log(arr1 == arr2);<br>console.log(arr1 === arr2);</pre><p>Output:</p><pre>false<br>false</pre><p>Even with loose equality (==), objects are compared by reference. Since arr1 and arr2 are different array instances, neither comparison returns true.</p><h3>Another Common Interview Question</h3><p>Consider the following code:</p><pre>const person = {<br>    name: &quot;Alice&quot;<br>};<br><br>function updateUser(user) {<br>    user.name = &quot;Bob&quot;;<br>}<br><br>updateUser(person);<br><br>console.log(person.name);</pre><h3>Output:</h3><pre>Bob</pre><p>Did JavaScript pass the object <strong>by reference</strong>?</p><p>Not exactly.</p><p>JavaScript is <strong>always pass-by-value</strong>.</p><p>For objects, the value being copied is the <strong>reference</strong> (memory address), not the object itself.</p><p>This means:</p><ul><li>A copy of the reference is passed to the function.</li><li>Both the original variable and the function parameter refer to the same object.</li><li>Mutating the object’s properties affects the shared object.</li><li>Reassigning the parameter to a new object does <strong>not</strong> affect the original variable.</li></ul><p>This distinction is subtle but extremely important.</p><h3>Reassigning the Parameter</h3><pre>const person = {<br>    name: &quot;Alice&quot;<br>};<br>function updateUser(user) {<br>    user = {<br>        name: &quot;Bob&quot;<br>    };<br>}<br>updateUser(person);<br>console.log(person.name);</pre><p>Output:</p><pre>Alice</pre><p>Here, user is reassigned to a completely new object. The original person variable still points to the original object, so it remains unchanged.</p><p>This is one of the clearest examples showing that JavaScript is <strong>not pass-by-reference</strong> — it is <strong>pass-by-value</strong>, where the value is sometimes a reference.</p><h3>Part 6 — Type Coercion, Equality, and JavaScript’s Weird Behaviors</h3><p>If you’ve ever seen something like this:</p><pre>console.log(&quot;5&quot; + 1);     // &quot;51&quot;<br>console.log(&quot;5&quot; - 1);     // 4<br>console.log([] == false); // true</pre><p>you’ve probably wondered:</p><blockquote><em>“How can the same language behave so inconsistently?”</em></blockquote><p>The answer is <strong>type coercion</strong>.</p><p>JavaScript is a <strong>dynamically typed language</strong>, which means variables are not permanently tied to a specific data type. As a result, JavaScript often converts values from one type to another automatically.</p><p>These automatic conversions are known as <strong>implicit type coercion</strong>.</p><p>When you convert a value yourself using functions like Number(), String(), or Boolean(), it is called <strong>explicit type coercion</strong>.</p><p>Understanding when JavaScript performs these conversions — and how — is essential for writing predictable code.</p><h3>Dynamic Typing</h3><p>Unlike statically typed languages such as Java or C++, JavaScript does not require you to specify the type of a variable.</p><p>For example:</p><pre>let value = 10;<br>value = &quot;JavaScript&quot;;<br>value = true;<br>value = null;</pre><p>The same variable stores four completely different types during its lifetime.</p><p>The JavaScript engine determines the type of the value at runtime rather than at compile time.</p><h3>Implicit Type Coercion</h3><p>Sometimes JavaScript converts values automatically.</p><p>Consider:</p><pre>console.log(&quot;10&quot; + 5);</pre><p>Output:</p><pre>105</pre><p>Why?</p><p>The + operator is overloaded in JavaScript. It performs either numeric addition or string concatenation.</p><p>Since one operand is a string, JavaScript converts the number 5 into the string &quot;5&quot; and concatenates the two values.</p><p>Internally, it’s similar to:</p><pre>&quot;10&quot; + String(5)</pre><p>Result:</p><pre>&quot;105&quot;</pre><h3>Numeric Operators Behave Differently</h3><p>Now look at subtraction.</p><pre>console.log(&quot;10&quot; - 5);</pre><p>Output:</p><pre>5</pre><p>Unlike the + operator, the - operator only performs numeric subtraction.</p><p>JavaScript therefore converts &quot;10&quot; into the number 10.</p><p>Conceptually:</p><pre>Number(&quot;10&quot;) - 5</pre><p>Result:</p><pre>5</pre><p>The same applies to:</p><pre>&quot;20&quot; * 2<br>&quot;20&quot; / 2<br>&quot;20&quot; % 3</pre><p>All of these operators force numeric conversion.</p><h3>Examples of Implicit Type Coercion</h3><pre>console.log(&quot;5&quot; + 1);</pre><p>Output</p><pre>51</pre><h3><strong>Explicit Type Conversion</strong></h3><p>Sometimes automatic conversion isn’t desirable.</p><p>JavaScript provides several built-in functions to convert values explicitly.</p><h3>Number()</h3><pre>Number(&quot;123&quot;)</pre><p>returns</p><pre>123</pre><h3>String()</h3><pre>String(123)</pre><p>returns</p><pre>&quot;123&quot;</pre><h3>Boolean()</h3><pre>Boolean(1)</pre><p>returns</p><pre>true</pre><h4>Trick to remember</h4><pre>string+anything -&gt; string<br>-,*,/ -&gt; always numbers<br>+ unary expression -&gt; number</pre><h3>Truthy and Falsy Values</h3><p>Whenever JavaScript evaluates a condition, it converts the value into either true or false. Surprisingly, almost every value in JavaScript is considered <strong>truthy</strong>. Only a small set of values are <strong>falsy</strong>.</p><p>The falsy values are:</p><pre>false<br><br>0<br><br>-0<br><br>0n<br><br>&quot;&quot;<br><br>null<br><br>undefined<br><br>NaN</pre><p>Everything else is truthy.</p><p>Example</p><pre>if ([]) {<br><br>    console.log(&quot;Runs&quot;);<br><br>}</pre><p>Output</p><pre>Runs</pre><p>An empty array is still an object, and all objects are truthy.</p><h3>Loose Equality (==)</h3><p>The loose equality operator compares values <strong>after performing type coercion when necessary</strong>.</p><p>Example:</p><pre>console.log(5 == &quot;5&quot;);</pre><p>Output</p><pre>true</pre><p>Internally, JavaScript converts:</p><pre>Number(&quot;5&quot;)</pre><p>into</p><pre>5</pre><p>Then compares:</p><pre>5 == 5</pre><h3>Strict Equality (===)</h3><p>The strict equality operator performs <strong>no type coercion</strong>.</p><p>Both the value and the type must be identical.</p><p>Example:</p><pre>console.log(5 === &quot;5&quot;);</pre><p>Output</p><pre>false</pre><p>because one operand is a number and the other is a string.</p><h3>When Should You Use ==?</h3><p>Modern JavaScript generally recommends using === because it avoids surprising type conversions.</p><p>There is, however, one common and intentional use of ==:</p><pre>if (value == null) {}</pre><p>This checks for both:</p><pre>null<br>undefined</pre><p>because</p><pre>null == undefined</pre><p>while no other values match.</p><p>This pattern is widely used when you want to check whether a value is “missing.”</p><h3>The typeof Operator</h3><p>The typeof operator tells you the type of a value.</p><p>Examples:</p><pre>typeof 42</pre><p>Output:</p><pre>&quot;number&quot;</pre><h3>The Famous typeof null Bug</h3><p>Now for one of JavaScript’s oldest quirks:</p><pre>console.log(typeof null);</pre><p>Output:</p><pre>&quot;object&quot;</pre><p>Many developers assume that null is an object.</p><p>It is <strong>not</strong>.</p><p>This behavior is a historical bug dating back to the very first implementation of JavaScript. Early versions used a low-level representation where object values and null shared the same type tag.</p><p>By the time this behavior was recognized as a mistake, millions of websites depended on it. Changing it would have broken the web, so the ECMAScript specification preserved the behavior for backward compatibility.</p><p>Even today:</p><pre>typeof null</pre><p>returns:</p><pre>&quot;object&quot;</pre><p>despite null being a primitive value.</p><h3>NaN — Not a Number</h3><p>NaN stands for <strong>Not a Number</strong>, but the name can be misleading.</p><p>It represents the result of an invalid numeric operation.</p><p>For example:</p><pre>Number(&quot;Hello&quot;)</pre><p>returns:</p><pre>NaN</pre><p>Similarly:</p><pre>0 / 0</pre><p>also produces:</p><pre>NaN</pre><p>One interesting property of NaN is that it is <strong>not equal to itself</strong>.</p><pre>console.log(NaN === NaN);</pre><p>Output:</p><pre>false</pre><p>This is defined by the IEEE 754 floating-point standard that JavaScript follows.</p><p>To check whether a value is NaN, use:</p><pre>Number.isNaN(value)</pre><p>instead of comparing directly with NaN.</p><pre>| JavaScript Quirk                    | One-line Explanation                                                                                           |<br>| ----------------------------------- | -------------------------------------------------------------------------------------------------------------- |<br>| `typeof null // &quot;object&quot;`           | Returns `&quot;object&quot;` due to a legacy bug in JavaScript that was never fixed for backward compatibility.          |<br>| `typeof NaN // &quot;number&quot;`            | `NaN` is a special numeric value representing an invalid number, so its type is `&quot;number&quot;`.                    |<br>| `NaN === NaN // false`              | `NaN` is the only value in JavaScript that is not equal to itself by design.                                   |<br>| `[] + [] // &quot;&quot;`                     | Both arrays are converted to empty strings, so the result is an empty string.                                  |<br>| `typeof [] // &quot;object&quot;`             | Arrays are a special type of object in JavaScript, so `typeof` returns `&quot;object&quot;`.                             |<br>| `typeof {} // &quot;object&quot;`             | Objects have the type `&quot;object&quot;` in JavaScript.                                                                |<br>| `typeof function(){} // &quot;function&quot;` | Functions are callable objects, so JavaScript gives them the special type `&quot;function&quot;`.                        |<br>| `[] + {} // &quot;[object Object]&quot;`      | The array becomes `&quot;&quot;` and the object becomes `&quot;[object Object]&quot;`, which are then concatenated.                |<br>| `{} + [] // 0`                      | At the start of a statement, `{}` is treated as an empty block, so only `+[]` is evaluated, which becomes `0`. |<br>| `true + true // 2`                  | In numeric operations, `true` is converted to `1`, so `1 + 1 = 2`.                                             |<br>| `null + 1 // 1`                     | `null` is converted to `0` in numeric operations, resulting in `1`.                                            |<br>| `undefined + 1 // NaN`              | `undefined` cannot be converted to a valid number, so the result is `NaN`.                                     |<br>| `Number(true) // 1`                 | `true` is converted to the number `1`.                                                                         |<br>| `Number(false) // 0`                | `false` is converted to the number `0`.                                                                        |<br>| `Number(null) // 0`                 | `null` is converted to the number `0` during numeric conversion.                                               |</pre><h3>Part 7 — Objects: The Building Blocks of JavaScript</h3><h3>What Is an Object?</h3><p>An object is a collection of <strong>key-value pairs</strong>.</p><p>Each key is called a <strong>property</strong>, and each property stores a value.</p><p>The value can be almost anything:</p><ul><li>A string</li><li>A number</li><li>A boolean</li><li>An array</li><li>Another object</li><li>Even a function</li></ul><p>For example:</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 24,<br>    isAdmin: false<br>};</pre><p>Here,</p><ul><li>name</li><li>age</li><li>isAdmin</li></ul><p>are properties of the object.</p><h3>Why Do We Need Objects?</h3><p>Imagine storing information about a user without objects.</p><pre>const name = &quot;Alice&quot;;<br>const age = 24;<br>const city = &quot;London&quot;;<br>const email = &quot;alice@gmail.com&quot;;</pre><p>As your application grows, managing related variables individually becomes difficult.</p><p>Instead, objects allow us to group related information together.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 24,<br>    city: &quot;London&quot;,<br>    email: &quot;alice@gmail.com&quot;<br>};</pre><p>Now everything related to the user exists in one place.</p><p>This improves readability, organization, and maintainability.</p><h3>Creating Objects in JavaScript</h3><p>Objects are one of the most fundamental data structures in JavaScript. They store data as <strong>key-value pairs</strong>, where each key is associated with a corresponding value.</p><pre>const person = {<br>    name: &quot;Alice&quot;,<br>    age: 25<br>};</pre><p>JavaScript provides multiple ways to create objects. Although they all create objects, each approach has different use cases, advantages, and trade-offs.</p><h3>1. Object Literal (Recommended)</h3><p>The most common and preferred way to create an object is by using <strong>object literal syntax</strong>.</p><pre>const car = {<br>    brand: &quot;BMW&quot;,<br>    model: &quot;M4&quot;,<br>    year: 2025<br>};</pre><p>This is equivalent to:</p><pre>const car = {};</pre><h3>Prototype</h3><p>Objects created using literal syntax automatically inherit from:</p><pre>Object.prototype</pre><p>Conceptually:</p><pre>car<br>↓<br>Object.prototype<br>↓<br>null</pre><p>Interestingly, the literal syntax {} is essentially shorthand for:</p><pre>new Object();</pre><p>although modern JavaScript engines optimize literal syntax heavily.</p><h3>Advantages</h3><ul><li>Short and concise</li><li>Easy to read</li><li>Fastest and most common way to create objects</li><li>Preferred in almost every real-world JavaScript project</li></ul><h3>Disadvantages</h3><p>If you’re creating many similar objects, object literals become repetitive because every object gets its own copy of methods.</p><p>Example:</p><pre>const user1 = {<br>    name: &quot;Alice&quot;,<br>    greet() {<br>        console.log(&quot;Hello&quot;);<br>    }<br>};<br>const user2 = {<br>    name: &quot;Bob&quot;,<br>    greet() {<br>        console.log(&quot;Hello&quot;);<br>    }<br>};</pre><p>Here, each object contains its own separate greet() function, which is inefficient when creating many objects. Constructor functions or classes allow methods to be shared through the prototype.</p><h3>2. Using new Object()</h3><p>Objects can also be created using the built-in Object constructor.</p><pre>const car = new Object();<br>car.brand = &quot;BMW&quot;;<br>car.model = &quot;M4&quot;;<br>car.year = 2025;</pre><p>This produces the same result as using an object literal.</p><h3>Prototype</h3><pre>car<br>↓<br>Object.prototype<br>↓<br>null</pre><h3>Advantages</h3><ul><li>Produces the same type of object as object literals</li><li>May help illustrate that objects are created through constructors</li></ul><h3>Disadvantages</h3><ul><li>More verbose</li><li>No practical advantage over object literals</li><li>Slightly slower because it invokes the constructor</li><li>Rarely used in modern JavaScript</li></ul><p>For these reasons, developers almost always prefer object literals.</p><h3>3. Using Object.create()</h3><p>Object.create() creates a new object whose prototype is explicitly specified.</p><pre>const animal = {<br>    speak() {<br>        console.log(&quot;Animal sound&quot;);<br>    }<br>};<br>const dog = Object.create(animal);<br>dog.name = &quot;Rocky&quot;;</pre><p>Now:</p><pre>dog.speak();</pre><p>Output:</p><pre>Animal sound</pre><p>The object inherits from animal.</p><p>Conceptually:</p><pre>dog<br>↓<br>animal<br>↓<br>Object.prototype<br>↓<br>null</pre><h3>Creating an Object Without a Prototype</h3><p>You can also create an object that has <strong>no prototype at all</strong>.</p><pre>const obj = Object.create(null);</pre><p>Now:</p><pre>console.log(obj.toString);</pre><p>Output:</p><pre>undefined</pre><p>Because the object doesn’t inherit from Object.prototype, it doesn&#39;t have built-in methods like:</p><ul><li>toString()</li><li>hasOwnProperty()</li><li>valueOf()</li></ul><p>Conceptually:</p><pre>obj<br>↓<br>null</pre><h3>Advantages</h3><ul><li>Excellent for prototype-based inheritance</li><li>Gives complete control over an object’s prototype</li><li>Useful for creating dictionary-like objects without inherited properties</li></ul><h3>Disadvantages</h3><ul><li>Can be confusing for beginners</li><li>Objects created with null as the prototype don&#39;t have common built-in methods</li><li>Some libraries expect objects to inherit from Object.prototype</li></ul><h3>4. Using Constructor Functions</h3><p>Before ES6 introduced classes, constructor functions were the standard way to create multiple similar objects.</p><pre>function User(name) {<br>    this.name = name;<br>}<br>const user1 = new User(&quot;Alice&quot;);<br>const user2 = new User(&quot;Bob&quot;);</pre><p>When used with the new keyword, JavaScript:</p><ol><li>Creates a new object.</li><li>Sets its prototype to User.prototype.</li><li>Binds this to the new object.</li><li>Executes the constructor.</li><li>Returns the object.</li></ol><p>This approach allows methods to be shared through the prototype instead of duplicating them for every instance.</p><h3>5. Using ES6 Classes</h3><p>ES6 introduced the class keyword, providing a cleaner syntax for creating objects.</p><pre>class User</pre><p>Although classes resemble object-oriented languages like Java or C++, they are built on top of JavaScript’s prototype system.</p><p>Conceptually:</p><pre>user1<br>↓<br>User.prototype<br>↓<br>Object.prototype<br>↓<br>null</pre><h3>Advantages</h3><ul><li>Cleaner and more organized syntax</li><li>Easier to understand for developers familiar with class-based languages</li><li>Supports inheritance using extends</li><li>Supports static methods and private fields</li></ul><h3>Disadvantages</h3><ul><li>Still uses prototypes internally, so understanding prototypes remains important</li></ul><h3>6. Creating Objects from JSON</h3><p>Objects can also be created by parsing JSON (JavaScript Object Notation).</p><pre>const json = &#39;{&quot;x&quot;:10,&quot;y&quot;:20}&#39;;<br>const obj = JSON.parse(json);<br>console.log(obj);</pre><p>Output:</p><pre>{<br>    x: 10,<br>    y: 20<br>}</pre><p>JSON is commonly used for:</p><ul><li>API responses</li><li>Configuration files</li><li>Data storage</li><li>Data exchange between applications</li></ul><h3>Advantages</h3><ul><li>Easy conversion from text to JavaScript objects</li><li>Widely used for client-server communication</li><li>Can be used for simple deep copies</li></ul><pre>const copy = JSON.parse(JSON.stringify(obj));</pre><h3>Limitations</h3><p>Using JSON.parse(JSON.stringify(obj)) for deep copying has several limitations:</p><ul><li>Functions are removed</li><li>Prototype information is lost</li><li>undefined values are omitted</li><li>Symbols are ignored</li><li>Date objects become strings</li><li>Map and Set are not preserved</li><li>Circular references throw an err</li></ul><p>Because of these limitations, modern JavaScript often uses structuredClone() (where supported) or dedicated cloning libraries for complex objects.</p><h3>Accessing Properties</h3><p>JavaScript provides two ways to access object properties.</p><h3>Dot Notation</h3><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(user.name);</pre><p>Output</p><pre>Alice</pre><p>Dot notation is the most common approach when you know the property name beforehand.</p><h3>Bracket Notation</h3><pre>console.log(user[&quot;name&quot;]);</pre><p>Output</p><pre>Alice</pre><p>Bracket notation is useful when the property name is stored in another variable.</p><p>Example:</p><pre>const key = &quot;name&quot;;<br>console.log(user[key]);</pre><p>Output</p><pre>Alice</pre><p>Notice that we used:</p><pre>user[key]</pre><p>and <strong>not</strong></p><pre>user.key</pre><p>Using user.key would literally look for a property named &quot;key&quot;.</p><h3>Adding New Properties</h3><p>Objects are mutable, which means new properties can be added at any time.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>user.age = 25;</pre><p>The object now becomes:</p><pre>{<br>    name: &quot;Alice&quot;,<br>    age: 25<br>}</pre><p>Similarly,</p><pre>user.city = &quot;London&quot;;</pre><p>adds another property.</p><h3>Updating Existing Properties</h3><p>Properties can also be modified.</p><pre>const user = {<br>    age: 24<br>};<br>user.age = 25;</pre><p>Now,</p><pre>console.log(user.age);</pre><p>prints</p><pre>25</pre><h3>Deleting Properties</h3><p>JavaScript provides the delete operator.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 24<br>};<br>delete user.age;</pre><p>Now the object becomes</p><pre>{<br>    name: &quot;Alice&quot;<br>}</pre><p>Notice that delete removes only the property.</p><p>It does <strong>not</strong> destroy the object itself.</p><h3>Nested Objects</h3><p>Objects can contain other objects.</p><p>Example:</p><pre>const student = {<br>name: &quot;John&quot;,<br>    address: {<br>        city: &quot;Delhi&quot;,<br>        state: &quot;Delhi&quot;<br>    }<br>};</pre><p>Accessing nested properties:</p><pre>console.log(student.address.city);</pre><p>Output</p><pre>Delhi</pre><p>Nested objects allow us to represent complex real-world data naturally.</p><h3>Objects Can Store Arrays</h3><p>Objects can also contain arrays.</p><pre>const student = {<br>name: &quot;John&quot;,<br>    skills: [<br>        &quot;JavaScript&quot;,<br>        &quot;React&quot;,<br>        &quot;Node&quot;<br>    ]<br>};</pre><p>Accessing array elements:</p><pre>console.log(student.skills[1]);</pre><p>Output</p><pre>React</pre><h3>Objects Can Store Functions</h3><p>One of JavaScript’s most powerful features is that functions are values.</p><p>This means they can be stored inside objects.</p><pre>const user = {<br>name: &quot;Alice&quot;,<br>    greet() {<br>        console.log(&quot;Hello!&quot;);<br>    }<br>};</pre><p>Calling the method:</p><pre>user.greet();</pre><p>Output</p><pre>Hello!</pre><p>A function stored as a property of an object is commonly referred to as a <strong>method</strong>.</p><h3>The this Keyword Inside Methods</h3><p>Consider:</p><pre>const user = {<br>name: &quot;Alice&quot;,<br>    greet() {<br>        console.log(this.name);<br>    }<br>};<br>user.greet();</pre><p>Output</p><pre>Alice</pre><p>Inside an object method, this refers to the object that invoked the method.</p><p>Here,</p><pre>this === user</pre><p>is true.</p><h3>Checking Whether a Property Exists</h3><p>Sometimes you need to determine whether an object contains a specific property.</p><p>One option is the in operator.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(&quot;name&quot; in user);</pre><p>Output:</p><pre>true</pre><p>Another example:</p><pre>console.log(&quot;age&quot; in user);</pre><p>Output:</p><pre>false</pre><p>The in operator checks both the object&#39;s own properties and those inherited through its prototype chain.</p><h3>Iterating Over Object Properties</h3><p>JavaScript provides the for...in loop for iterating over an object&#39;s enumerable properties.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 25,<br>    city: &quot;London&quot;<br>};<br>for (const key in user) {<br>    console.log(key, user[key]);<br>}</pre><pre>name Alice<br>age 25<br>city London</pre><p>Notice that we use:</p><pre>user[key]</pre><p>instead of:</p><pre>user.key</pre><p>because key is a variable whose value changes during each iteration.</p><h3>Enumerating Object Properties</h3><p>JavaScript also provides built-in methods for retrieving an object’s properties.</p><pre>Object.keys(user); -&gt; [&quot;name&quot;, &quot;age&quot;, &quot;city&quot;]</pre><pre>Object.values(user); -&gt; [&quot;Alice&quot;, 25, &quot;London&quot;]</pre><pre>Object.entries(user);<br><br><br>[    [&quot;name&quot;, &quot;Alice&quot;],<br>    [&quot;age&quot;, 25],<br>    [&quot;city&quot;, &quot;London&quot;]<br>]</pre><p>These methods are especially useful when working with loops, APIs, and data transformation.</p><h3>Objects Are Mutable</h3><p>One common misconception is that declaring an object with const makes it immutable.</p><p>Consider:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>user.name = &quot;Bob&quot;;</pre><p>Does this throw an error?</p><p>No.</p><p>The output is:</p><pre>{<br>    name: &quot;Bob&quot;<br>}</pre><p>Why?</p><p>Because const prevents <strong>reassignment of the variable</strong>, not modification of the object it references.</p><p>This, however, is <strong>not allowed</strong>:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>user = {<br>    name: &quot;Bob&quot;<br>};</pre><p>Output:</p><pre>TypeError: Assignment to constant variable.</pre><p>The reference stored in user cannot be changed, but the object itself remains mutable.</p><h3>Common Object Methods Every JavaScript Developer Should Know</h3><p>JavaScript provides several built-in methods for checking, accessing, copying, and iterating over object properties. Understanding these methods is essential because you’ll encounter them frequently in real-world applications.</p><p>Let’s explore the most commonly used ones.</p><h3>Checking Whether a Property Exists</h3><p>There are three common ways to determine whether an object contains a property.</p><p>Although they may appear similar, they behave differently.</p><h3>The in Operator</h3><p>The in operator checks whether a property exists anywhere in the object, including its prototype chain.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(&quot;name&quot; in user);</pre><p>Output:</p><pre>true</pre><p>It also checks inherited properties.</p><pre>console.log(&quot;toString&quot; in user);</pre><p>Output:</p><pre>true</pre><p>Even though toString isn&#39;t defined directly on user, it exists on Object.prototype.</p><h3>Common Uses</h3><ul><li>Checking whether a property exists on an object.</li><li>Iterating over objects using a for...in loop.</li><li>Detecting inherited properties.</li></ul><h3>Using in with Arrays</h3><p>Many beginners forget that arrays are actually specialized objects.</p><pre>const numbers = [10, 20, 30];<br>console.log(0 in numbers);<br>console.log(1 in numbers);<br>console.log(2 in numbers);<br>console.log(3 in numbers);</pre><p>Output:</p><pre>true<br>true<br>true<br>false</pre><p>Why?</p><p>Internally, arrays store elements as object properties whose keys are their indices.</p><p>Conceptually:</p><pre>const numbers = {<br>    0: 10,<br>    1: 20,<br>    2: 30<br>};</pre><p>Therefore, the in operator checks whether those index properties exist.</p><h3>hasOwnProperty()</h3><p>Sometimes you only want to know whether a property belongs directly to the object itself.</p><p>That’s what hasOwnProperty() is for.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(user.hasOwnProperty(&quot;name&quot;));</pre><p>Output:</p><pre>true</pre><p>Checking an inherited property:</p><pre>console.log(user.hasOwnProperty(&quot;toString&quot;));</pre><p>Output:</p><pre>false</pre><p>Unlike the in operator, hasOwnProperty() ignores inherited properties.</p><h3>Characteristics</h3><ul><li>Checks <strong>own properties only</strong></li><li>Ignores inherited properties</li><li>Non-static method (called on the object itself)</li></ul><h3>Object.hasOwn()</h3><p>Modern JavaScript introduced a cleaner alternative.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(Object.hasOwn(user, &quot;name&quot;));</pre><p>Output:</p><pre>true</pre><p>This behaves similarly to hasOwnProperty(), but it&#39;s a <strong>static method</strong> on the Object constructor.</p><h3>Why is it preferred?</h3><p>Objects created with:</p><pre>Object.create(null);</pre><p>don’t inherit from Object.prototype, so they don&#39;t have a hasOwnProperty() method.</p><p>However,</p><pre>Object.hasOwn(obj, key);</pre><p>works regardless of the object’s prototype.</p><h3>Characteristics</h3><ul><li>Checks <strong>own properties only</strong></li><li>Ignores inherited properties</li><li>Static method</li><li>Safer for objects with null prototypes</li></ul><h3>Object.keys()</h3><p>Object.keys() returns an array containing the object&#39;s own enumerable property names.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 25,<br>    city: &quot;London&quot;<br>};<br>console.log(Object.keys(user));</pre><p>Output:</p><pre>[<br>    &quot;name&quot;,<br>    &quot;age&quot;,<br>    &quot;city&quot;<br>]</pre><p>The keys appear in the same order they were inserted into the object.</p><h3>Includes</h3><ul><li>Own properties</li><li>Enumerable properties</li><li>String keys</li></ul><h3>Does Not Include</h3><ul><li>Non-enumerable properties</li><li>Symbol keys</li><li>Inherited properties</li></ul><h3>Object.values()</h3><p>Object.values() returns an array containing the values of the object&#39;s own enumerable properties.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 25<br>};<br>console.log(Object.values(user));</pre><p>Output:</p><pre>[<br>    &quot;Alice&quot;,<br>    25<br>]</pre><h3>Includes</h3><ul><li>Values of own enumerable properties</li></ul><h3>Does Not Include</h3><ul><li>Non-enumerable properties</li><li>Symbol keys</li><li>Inherited properties</li></ul><h3>Object.entries()</h3><p>Object.entries() returns an array of key-value pairs.</p><p>Each entry is itself a two-element array.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 25<br>};<br>console.log(Object.entries(user));</pre><p>Output:</p><pre>[<br>    [&quot;name&quot;, &quot;Alice&quot;],<br>    [&quot;age&quot;, 25]<br>]</pre><p>This method is particularly useful when iterating over both keys and values.</p><p>Example:</p><pre>for (const [key, value] of Object.entries(user)) {<br>console.log(key, value);<br>}</pre><p>Output:</p><pre>name Alice<br>age 25</pre><h3>Includes</h3><ul><li>Own enumerable properties</li><li>Both keys and values</li></ul><h3>Object.getOwnPropertyNames()</h3><p>Unlike Object.keys(), this method also includes <strong>non-enumerable</strong> property names.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(Object.getOwnPropertyNames(user));</pre><p>Output:</p><pre>[<br>    &quot;name&quot;<br>]</pre><p>A better demonstration:</p><pre>const user = {};<br>Object.defineProperty(user, &quot;id&quot;, {<br>    value: 101,<br>    enumerable: false<br>});<br>console.log(Object.keys(user));<br>console.log(Object.getOwnPropertyNames(user));</pre><p>Output:</p><pre>[]<br>[&quot;id&quot;]</pre><h3>Includes</h3><ul><li>Own enumerable properties</li><li>Own non-enumerable properties</li></ul><h3>Does Not Include</h3><ul><li>Symbol properties</li><li>Inherited properties</li></ul><p>If you also need Symbol properties, use:</p><pre>Object.getOwnPropertySymbols(obj);</pre><p>or</p><pre>Reflect.ownKeys(obj);</pre><h3>Object.assign()</h3><p>Object.assign() copies properties from one or more source objects into a target object.</p><p>Syntax:</p><pre>Object.assign(target, ...sources);</pre><p>Where:</p><ul><li><strong>target</strong> → receives the copied properties.</li><li><strong>sources</strong> → one or more objects whose properties will be copied.</li></ul><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>const details = {<br>    age: 25,<br>    city: &quot;London&quot;<br>};<br>Object.assign(user, details);<br>console.log(user);</pre><p>Output:</p><pre>{<br>    name: &quot;Alice&quot;,<br>    age: 25,<br>    city: &quot;London&quot;<br>}</pre><p>The target object is modified and also returned.</p><pre>const result = Object.assign(user, details);<br>console.log(result === user);</pre><p>Output:</p><pre>true</pre><h3>Multiple Source Objects</h3><pre>const obj = Object.assign(<br>    {},<br>    { a: 1 },<br>    { b: 2 },<br>    { c: 3 }<br>);<br>console.log(obj);</pre><p>Output:</p><pre>{<br>    a: 1,<br>    b: 2,<br>    c: 3<br>}</pre><h3>Important: It Performs a Shallow Copy</h3><p>Object.assign() copies only the first level of properties.</p><pre>const user = {<br>    profile: {<br>        age: 25<br>    }<br>};<br>const copy = Object.assign({}, user);<br>copy.profile.age = 30;<br>console.log(user.profile.age);</pre><p>Output:</p><pre>30</pre><p>Both objects still reference the same nested object.</p><p>For a true deep copy, consider using structuredClone() (where supported) or a dedicated deep-cloning utility.</p><h3>A Common Interview Question</h3><p>What does the following code print?</p><pre>const obj = {<br>    a: 1<br>};<br>const copy = obj;<br>copy.a = 10;<br>console.log(obj.a);</pre><p>Output:</p><pre>10</pre><p>Why?</p><p>Because obj and copy refer to the <strong>same object</strong> in memory. Changing a property through one reference affects the shared object.</p><h3>Why Don’t JavaScript Objects Always Maintain Insertion Order?</h3><p>A common misconception is that JavaScript objects do <strong>not</strong> maintain the order in which properties are inserted.</p><p>In reality, <strong>modern JavaScript does preserve property order</strong>, but <strong>not purely in insertion order</strong>. Instead, the ECMAScript specification defines precise rules that determine how properties are stored and returned during enumeration.</p><p>To understand this behavior, we first need to understand what happens when a property is added to an object.</p><h3>What Happens When a Property Is Inserted?</h3><p>Suppose we create an object like this:</p><pre>const obj = {};<br>obj[&quot;name&quot;] = &quot;Alice&quot;;<br>obj[10] = &quot;ten&quot;;<br>obj[true] = &quot;yes&quot;;<br>obj[null] = &quot;nothing&quot;;</pre><p>Whenever a property is added, JavaScript immediately performs an internal operation called <strong>ToPropertyKey</strong>.</p><p>Its job is to convert the supplied key into a valid JavaScript property key.</p><p>A property key can only be one of two types:</p><ul><li><strong>String</strong></li><li><strong>Symbol</strong></li></ul><p>If the supplied key is not already a string or a Symbol, JavaScript converts it into a string before storing it.</p><p>Conceptually:</p><pre>Insert Property<br>↓<br>ToPropertyKey(key)<br>↓<br>String or Symbol<br>↓<br>Store in Object</pre><p>This conversion happens <strong>at insertion time</strong>, not later when the property is accessed.</p><h3>The ToPropertyKey and ToString Internal Operations</h3><p>ToPropertyKey is an <strong>internal abstract operation</strong> defined by the ECMAScript specification.</p><p>If the value isn’t already a string or a Symbol, ToPropertyKey internally uses another abstract operation called <strong>ToString</strong> to convert it into a string.</p><p>For example:</p><pre>const obj = {};<br>obj[true] = &quot;value&quot;;<br>obj[null] = &quot;value&quot;;<br>obj[undefined] = &quot;value&quot;;<br>obj[123] = &quot;value&quot;;<br>console.log(obj);</pre><p>Conceptually, JavaScript stores this as:</p><pre>{<br>    &quot;true&quot;: &quot;value&quot;,<br>    &quot;null&quot;: &quot;value&quot;,<br>    &quot;undefined&quot;: &quot;value&quot;,<br>    &quot;123&quot;: &quot;value&quot;<br>}</pre><p>Notice that every key has become a string.</p><h3>ToString vs .toString()</h3><p>These two names look similar but represent completely different concepts.</p><h3>Internal ToString</h3><ul><li>Defined by the ECMAScript specification.</li><li>Used internally by the JavaScript engine.</li><li>Converts values into strings during operations such as property insertion.</li><li>Cannot be called directly.</li></ul><h3>.toString() Method</h3><pre>const num = 42;<br>console.log(num.toString());</pre><p>This is a normal JavaScript method inherited from an object’s prototype.</p><p>Although they often produce similar results, the internal <strong>ToString abstract operation</strong> and the .toString() method are <strong>not the same thing</strong>.</p><p>This explains why keys such as null and undefined become &quot;null&quot; and &quot;undefined&quot; when used as object property names, even though null and undefined do not have their own .toString() methods that you can call directly.</p><h3>How Are Properties Stored Internally?</h3><p>The ECMAScript specification doesn’t require JavaScript engines to use any specific data structure internally.</p><p>An engine might use hash tables, hidden classes, dictionaries, or other optimized representations depending on the situation.</p><p>What the specification <em>does</em> define is the observable behavior.</p><p>Conceptually, JavaScript maintains an internal list of properties that follows these categories:</p><ul><li>Integer-like property keys</li><li>String property keys</li><li>Symbol property keys</li></ul><p>JavaScript engines use these categories to determine the order in which properties are returned.</p><h3>Property Enumeration Order</h3><p>When you iterate over an object using methods such as:</p><ul><li>Object.keys()</li><li>Object.values()</li><li>Object.entries(</li><li>for...in</li><li>Reflect.ownKeys() (with slightly different behavior)</li></ul><p>JavaScript follows these ordering rules:</p><h3>1. Integer-like keys</h3><p>Property names that represent non-negative integers are returned first.</p><p>They are sorted in <strong>ascending numeric order</strong>, regardless of the order in which they were inserted.</p><p>Example:</p><pre>const obj = {};<br>obj[10] = &quot;ten&quot;;<br>obj[2] = &quot;two&quot;;<br>obj[1] = &quot;one&quot;;<br>console.log(Object.keys(obj));</pre><p>Output:</p><pre>[<br>    &quot;1&quot;,<br>    &quot;2&quot;,<br>    &quot;10&quot;<br>]</pre><p>Even though 10 was inserted first, the numeric keys are sorted before being returned.</p><h3>2. String Keys</h3><p>After all integer-like keys have been returned, normal string keys are returned.</p><p>These preserve their original insertion order.</p><p>Example:</p><pre>const obj = {};<br>obj.name = &quot;Alice&quot;;<br>obj.city = &quot;London&quot;;<br>obj.country = &quot;UK&quot;;<br>console.log(Object.keys(obj));</pre><p>Output:</p><pre>[<br>    &quot;name&quot;,<br>    &quot;city&quot;,<br>    &quot;country&quot;<br>]</pre><h3>3. Symbol Keys</h3><p>Finally, Symbol properties are returned.</p><p>Like string properties, they preserve their insertion order.</p><pre>const id1 = Symbol(&quot;id1&quot;);<br>const id2 = Symbol(&quot;id2&quot;);<br>const obj = {};<br>obj[id1] = 1;<br>obj[id2] = 2;</pre><p>When Symbol properties are enumerated (for example, using Object.getOwnPropertySymbols()), they appear in the order they were added.</p><p>Example:</p><pre>const obj = {};<br>obj[&quot;b&quot;] = 1;<br>obj[10] = 2;<br>obj[&quot;a&quot;] = 3;<br>obj[2] = 4;<br>console.log(Object.keys(obj));</pre><p>Output:</p><pre>[<br>    &quot;2&quot;,<br>    &quot;10&quot;,<br>    &quot;b&quot;,<br>    &quot;a&quot;<br>]</pre><p>Notice the ordering:</p><ol><li>Integer-like keys (2, 10) appear first in ascending numeric order.</li><li>String keys (b, a) appear afterward in the order they were inserted.</li></ol><h3>Property Descriptors</h3><p>In JavaScript, every property (key) of an object has some hidden metadata called <strong>property descriptors</strong>. These descriptors control how the property behaves.</p><p>Normally, when you add properties like this:</p><pre>obj.key = value;<br>obj[key] = value;</pre><p>JavaScript automatically creates the property with default descriptor values.</p><p>However, if you need more control over a property’s behavior, you can use Object.defineProperty().</p><p>It allows you to:</p><ul><li>Make a property <strong>read-only</strong></li><li>Make a property <strong>non-enumerable</strong> (hidden from loops and Object.keys())</li><li>Make a property <strong>non-configurable</strong> (cannot be deleted or redefined)</li><li>Create <strong>getter</strong> and <strong>setter</strong> properties</li></ul><h3>Property Descriptor Attributes</h3><h3>value</h3><p>The actual value stored in the property.</p><h3>writable</h3><p>Determines whether the property’s value can be changed.</p><ul><li>true → Value can be modified.</li><li>false → Property becomes read-only.</li></ul><h3>enumerable</h3><p>Determines whether the property appears during enumeration.</p><ul><li>true → Appears in for...in, Object.keys(), etc.</li><li>false → Hidden from enumeration.</li></ul><h3>configurable</h3><p>Determines whether the property can be deleted or redefined.</p><ul><li>true → Can be deleted or reconfigured.</li><li>false → Cannot be deleted or redefined.</li></ul><h3>Syntax</h3><pre>Object.defineProperty(objectName, propertyName, {<br>    value: someValue,<br>    writable: true,<br>    enumerable: true,<br>    configurable: true<br>});</pre><blockquote><strong><em>Note:</em></strong><em> Unlike normal property assignment, the descriptor flags (</em><em>writable, </em><em>enumerable, and </em><em>configurable) default to </em><strong><em>false</em></strong><em> when omitted in </em><em>Object.defineProperty(). This is because JavaScript assumes you&#39;re intentionally creating a property with special behavior.</em></blockquote><p>Example</p><pre>const user = {};<br>Object.defineProperty(user, &quot;id&quot;, {<br>    value: 101,<br>    writable: false,<br>    enumerable: true,<br>    configurable: false<br>});<br>console.log(user.id);</pre><p>Output:</p><pre>101</pre><p>Attempting to modify or delete id will fail (or throw an error in strict mode) because of its descriptor settings.</p><h3>Viewing Property Descriptors</h3><p>You can inspect a property’s descriptors using:</p><pre>Object.getOwnPropertyDescriptor(obj, &quot;key&quot;);</pre><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(<br>    Object.getOwnPropertyDescriptor(user, &quot;name&quot;)<br>);</pre><p>Output:</p><pre>{<br>    value: &quot;Alice&quot;,<br>    writable: true,<br>    enumerable: true,<br>    configurable: true<br>}</pre><h3>Arrays in JavaScript</h3><p>An <strong>array</strong> is an ordered collection of values that allows you to store multiple items in a single variable.</p><p>Unlike arrays in languages such as C or C++, JavaScript arrays are <strong>automatically resizable</strong>, meaning they do not have a fixed size. You can add or remove elements at any time without manually managing memory.</p><pre>const numbers = [10, 20, 30];</pre><h3>How Arrays Work Internally</h3><p>Although arrays look like a separate data structure, they are actually <strong>specialized objects</strong> in JavaScript.</p><p>Internally, array indices are stored as numeric property keys.</p><pre>const arr = [10, 20];</pre><p>Conceptually, JavaScript treats it like:</p><pre>{<br>    &quot;0&quot;: 10,<br>    &quot;1&quot;: 20,<br>    length: 2<br>}</pre><p>So,</p><pre>arr[0]</pre><p>is essentially accessing the property:</p><pre>arr[&quot;0&quot;]</pre><p>Modern JavaScript engines (such as Google’s V8) heavily optimize arrays behind the scenes, especially when they contain continuous numeric indices (called <strong>dense arrays</strong>), making them much faster than ordinary objects.</p><h3>Sparse Arrays (Arrays with Holes)</h3><p>Unlike arrays in many programming languages, JavaScript allows missing elements.</p><pre>const arr = [1, , 3];</pre><p>Output:</p><pre>[<br>    1,<br>    &lt;empty&gt;,<br>    3<br>]</pre><p>The missing position is called a <strong>hole</strong>.</p><p>Because JavaScript arrays are objects rather than continuous blocks of memory, they can contain holes, mixed data types, and dynamically grow or shrink.</p><p>This flexibility makes JavaScript arrays more versatile, although they are generally slower than low-level language arrays designed for purely numeric data.</p><h3>Memory Allocation</h3><p>Like all other <strong>non-primitive</strong> values in JavaScript, arrays are allocated on the <strong>Heap</strong>. The variable itself stores only a reference to the array.</p><p>Conceptually:</p><pre>Stack<br>arr<br> │<br> ▼<br>Heap<br>[10, 20, 30]</pre><p>This is why assigning one array to another copies only the reference, not the array itself.</p><h3>Ways to Create Arrays</h3><p>JavaScript provides several ways to create arrays.</p><h3>1. Array Literal (Recommended)</h3><p>The simplest and most common approach is using array literal syntax.</p><pre>const arr = [10, 20, 30];</pre><h3>Advantages</h3><ul><li>Short and readable</li><li>Fastest and most commonly used</li><li>Preferred in almost all real-world code</li></ul><h3>2. Using the Array Constructor</h3><pre>const arr = new Array(10, 20, 30);</pre><p>This creates:</p><pre>[<br>    10,<br>    20,<br>    30<br>]</pre><h3>Special Case</h3><p>If only <strong>one numeric argument</strong> is provided,</p><pre>const arr = new Array(5);</pre><p>JavaScript interprets it as the desired length rather than an element.</p><p>Output:</p><pre>[ &lt;5 empty items&gt; ]</pre><p>This creates an empty array with a length of 5.</p><h3>3. Using Array.of()</h3><p>Array.of() always treats its arguments as array elements.</p><pre>const arr = Array.of(3);</pre><p>Output:</p><pre>[<br>    3<br>]</pre><p>Unlike the Array constructor,</p><pre>Array.of(3);</pre><p>creates an array containing 3, rather than an empty array of length 3.</p><p>It accepts any number of comma-separated values.</p><pre>const arr = Array.of(10, 20, 30);</pre><h3>4. Using Array.from()</h3><p>Array.from() creates an array from <strong>iterable</strong> or <strong>array-like</strong> objects.</p><p>Example:</p><pre>Array.from(&quot;hello&quot;);</pre><p>Output:</p><pre>[<br>    &quot;h&quot;,<br>    &quot;e&quot;,<br>    &quot;l&quot;,<br>    &quot;l&quot;,<br>    &quot;o&quot;<br>]</pre><p>It works with:</p><ul><li>Strings</li><li>Sets</li><li>Maps</li><li>NodeList</li><li>arguments</li><li>Array-like objects</li></ul><p>Example:</p><pre>const obj = {<br>    0: &quot;a&quot;,<br>    1: &quot;b&quot;,<br>    length: 2<br>};<br>console.log(Array.from(obj));</pre><p>Output:</p><pre>[<br>    &quot;a&quot;,<br>    &quot;b&quot;<br>]</pre><h3>Common Array Methods</h3><p>JavaScript arrays provide many built-in methods for adding, removing, searching, transforming, and iterating over elements.</p><h3>push()</h3><p>Adds one or more elements to the end of an array.</p><p>Returns the <strong>new length</strong> of the array.</p><pre>const arr = [1, 2];<br>arr.push(3, 4);</pre><h3>pop()</h3><p>Removes and returns the last element.</p><pre>arr.pop();</pre><h3>shift()</h3><p>Removes and returns the first element.</p><pre>arr.shift();</pre><h3>unshift()</h3><p>Adds one or more elements to the beginning of the array.</p><p>Returns the new length.</p><pre>arr.unshift(0);</pre><h3>find()</h3><p>Returns the <strong>first element</strong> that satisfies a condition.</p><p>If no element matches, it returns undefined.</p><pre>arr.find(num =&gt; num &gt; 5);</pre><h3>findIndex()</h3><p>Returns the index of the first matching element.</p><p>Returns -1 if no match is found.</p><pre>arr.findIndex(num =&gt; num &gt; 5);</pre><h3>indexOf()</h3><p>Returns the first occurrence of a value.</p><p>Returns -1 if the value isn&#39;t found.</p><pre>arr.indexOf(20);</pre><h3>lastIndexOf()</h3><p>Searches from the end of the array and returns the last matching index.</p><pre>arr.lastIndexOf(20);</pre><h3>includes()</h3><p>Checks whether an element exists in the array.</p><p>Returns true or false.</p><pre>arr.includes(10);</pre><h3>every()</h3><p>Returns true only if <strong>every</strong> element satisfies the given condition.</p><pre>arr.every(num =&gt; num &gt; 0);</pre><h3>some()</h3><p>Returns true if <strong>at least one</strong> element satisfies the condition.</p><pre>arr.some(num =&gt; num &gt; 100);</pre><h3>sort()</h3><p>Sorts the array <strong>in place</strong>.</p><p>By default, elements are sorted as <strong>strings</strong>, not numbers.</p><pre>const arr = [100, 5, 20];<br></pre><p>Output:</p><pre>[<br>    100,<br>    20,<br>    5<br>]</pre><p>For numeric sorting:</p><pre>arr.sort((a, b) =&gt; a - b);</pre><h3>reverse()</h3><p>Reverses the order of elements in the original array.</p><pre>arr.reverse();</pre><h3>slice()</h3><p>Extracts part of an array and returns a <strong>new array</strong>.</p><p>Syntax:</p><pre>array.slice(start, end);</pre><ul><li>start → inclusive</li><li>end → exclusive</li></ul><pre>const arr = [1, 2, 3, 4];<br>arr.slice(1, 3);</pre><p>Output:</p><pre>[<br>    2,<br>    3<br>]</pre><h3>Characteristics</h3><ul><li>Returns a new array</li><li>Does <strong>not</strong> modify the original array</li></ul><h3>splice()</h3><p>Adds, removes, or replaces elements in the original array.</p><p>Syntax:</p><pre>array.splice(start, deleteCount, item1, item2, ...);</pre><ul><li>start → index to begin modification</li><li>deleteCount → number of elements to remove</li><li>Remaining arguments → elements to insert</li></ul><p>Example:</p><pre>const arr = [1, 2, 3];<br>arr.splice(1, 1, 100);</pre><p>Output:</p><pre>[<br>    1,<br>    100,<br>    3<br>]</pre><h3>Characteristics</h3><ul><li>Modifies the original array</li><li>Can insert, remove, or replace elements</li></ul><h3>concat()</h3><p>Combines multiple arrays or values into a <strong>new array</strong>.</p><pre>const arr1 = [1, 2];<br>const arr2 = [3, 4];<br>const result = arr1.concat(arr2);</pre><p>Output:</p><pre>[<br>    1,<br>    2,<br>    3,<br>    4<br>]</pre><h3>Characteristics</h3><ul><li>Returns a new array</li><li>Does not modify the original array</li></ul><h3>fill()</h3><p>Fills all or part of an array with a specified value.</p><p>Syntax:</p><pre>array.fill(value, start, end);</pre><ul><li>value → value to fill</li><li>start → starting index (inclusive, optional)</li><li>end → ending index (exclusive, optional)</li></ul><p>Example:</p><pre>const arr = [1, 2, 3, 4];<br>arr.fill(0);</pre><p>Output:</p><pre>[<br>    0,<br>    0,<br>    0,<br>    0<br>]</pre><p>Filling only part of the array:</p><pre>const arr = [1, 2, 3, 4];<br>arr.fill(9, 1, 3);</pre><p>Output:</p><pre>[<br>    1,<br>    9,<br>    9,<br>    4<br>]</pre><p>fill() modifies the original array and is commonly used to initialize arrays with default values.</p><h3>Mutating vs Non-Mutating Methods</h3><p>One of the most important things to remember is whether an array method modifies the original array.</p><h3>Mutating Methods</h3><ul><li>push()</li><li>pop()</li><li>shift()</li><li>unshift()</li><li>splice()</li><li>sort()</li><li>reverse()</li><li>fill()</li></ul><p>These methods change the original array.</p><h3>Non-Mutating Methods</h3><ul><li>slice()</li><li>concat()</li><li>find()</li><li>findIndex()</li><li>includes()</li><li>indexOf()</li><li>lastIndexOf()</li><li>every()</li><li>some()</li></ul><p>These methods leave the original array unchanged and either return a new array or another value.</p><h3><strong>Part 8 — Modern JavaScript: Destructuring, Spread, Rest, Optional Chaining, and Nullish Coalescing</strong></h3><p>When ES6 was released, JavaScript received some of its biggest improvements since the language was created.</p><p>Before ES6, developers often had to write repetitive code just to extract object properties, copy arrays, or safely access nested values.</p><p>Modern JavaScript introduced elegant syntax that dramatically reduced boilerplate while making code more expressive.</p><p>Let’s explore these features one by one.</p><h3>Destructuring</h3><p>Destructuring allows us to extract values from objects or arrays and assign them directly to variables.</p><p>Instead of manually accessing each property, JavaScript can unpack values in a single statement.</p><h3>Iterables Destructuring</h3><p>Let’s start with the most common iterable — an array.</p><pre>const colors = [&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;];</pre><p>Instead of:</p><pre>const first = colors[0];<br>const second = colors[1];</pre><p>we can write:</p><pre>const [first, second] = colors;</pre><p>Output:</p><pre>Red<br>Green</pre><p><strong>String destructuring</strong></p><pre>const [a, b] = &quot;Hi&quot;;</pre><p><strong>Set destructuring</strong></p><pre>const [x, y] = new Set([10, 20, 30]);</pre><p><strong>Map destructuring</strong></p><pre>const [[key, value]] = new Map([[&quot;name&quot;, &quot;John&quot;]]);</pre><p><strong>Object Destructuring</strong></p><p>Example</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 24,<br>    country: &quot;India&quot;<br>};</pre><p>Instead of:</p><pre>const name = user.name;<br>const age = user.age;<br>const country = user.country;</pre><p>we can write:</p><pre>const { name, age, country } = user;</pre><p>which is much shorter and easier to read.</p><p><strong>Nested Object Destructuring</strong></p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    address: {<br>        city: &quot;Delhi&quot;,<br>        country: &quot;India&quot;<br>    }<br>};</pre><p>Instead of writing:</p><pre>console.log(user.address.city);</pre><p>we can write:</p><pre>const { ddress: { city } } = user;<br>console.log(city);</pre><p>Output:</p><pre>Delhi</pre><h3>Renaming Variables While Destructuring</h3><p>Sometimes you don’t want the variable name to match the property name.</p><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>const { name: fullName } = user;<br>console.log(fullName);</pre><p>Output:</p><pre>Alice</pre><p>Here,</p><ul><li>name is the property.</li><li>fullName is the new variable.</li></ul><p>The original object remains unchanged.</p><h3>Default Values</h3><p>Sometimes a property doesn’t exist.</p><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>const { age = 18 } = user;<br>console.log(age);</pre><p>Output:</p><pre>18</pre><p>Since age wasn&#39;t found, JavaScript used the default value.</p><p>If the property does exist, the default is ignored.</p><h3>Skipping Values</h3><p>Suppose we only need the first and third values.</p><pre>const colors = [&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;];</pre><p>We can skip elements.</p><pre>const [first, , third] = colors;</pre><p>Output:</p><pre>Red<br>Blue</pre><h3>Swapping Variables</h3><p>Before destructuring, swapping values required a temporary variable.</p><pre>let a = 10;<br>let b = 20;<br>let temp = a;<br>a = b;<br>b = temp;</pre><p>Modern JavaScript makes this much cleaner.</p><pre>let a = 10;<br>let b = 20;<br>[a, b] = [b, a];</pre><p>Output:</p><pre>a = 20<br>b = 10</pre><h3>The Spread Operator (...)</h3><p>The spread operator expands an iterable into individual elements.</p><p>Although the syntax consists of three dots (...), its meaning depends on the context in which it is used.</p><p>Let’s begin with arrays.</p><h3>Copying Arrays</h3><p>Suppose we have:</p><pre>const numbers = [1, 2, 3];</pre><p>Many beginners write:</p><pre>const copy = numbers;</pre><p>However, this does <strong>not</strong> create a new array.</p><p>Instead:</p><pre>numbers ───────┐<br>               │<br>copy ──────────┘<br>               │<br>               ▼<br>          [1, Both variables point to the same array.</pre><p>If we modify one,</p><pre>copy.push(4)<br>console.log(numbers);<br>[1, 2, 3, 4]</pre><p>because both variables reference the same array.</p><p>Using the spread operator solves this.</p><pre>const copy = [...numbers];</pre><p>Now JavaScript creates a brand-new array.</p><h3>Merging Arrays</h3><p>Spread also makes merging arrays simple.</p><pre>const frontend = [&quot;HTML&quot;, &quot;CSS&quot;];<br>const backend = [&quot;Node&quot;, &quot;Express&quot;];<br>const skills = [...frontend, ...backend];</pre><p>Output:</p><pre>[&quot;HTML&quot;, &quot;CSS&quot;, &quot;Node&quot;, &quot;Express&quot;]</pre><h3>Copying Objects</h3><p>Objects behave similarly.</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>const copy = {<br>    ...user<br>};</pre><p>This creates a new object with the same properties.</p><p>Remember that this is a <strong>shallow copy</strong>.</p><p>We’ll discuss shallow vs deep copies shortly.</p><h3>Merging Objects</h3><p>Spread also allows us to merge multiple objects.</p><pre>const personal = {<br>    name: &quot;Alice&quot;<br>};<br>const professional = {<br>    role: &quot;Developer&quot;<br>};<br>const profile = {<br>    ...personal,<br>    ...professional<br>};</pre><p>Output:</p><pre>{<br>    name: &quot;Alice&quot;,<br>    role: &quot;Developer&quot;<br>}</pre><h3>What Happens When Keys Conflict?</h3><p>Consider:</p><pre>const a = {<br>    age: 20<br>};<br>const b = {<br>    age: 30<br>};<br>const user = {<br>    ...a,<br>    ...b<br>};</pre><p>Output:</p><pre>{<br>    age: 30<br>}</pre><p>When duplicate keys exist, the <strong>last value wins</strong>.</p><p>This behavior is commonly used when overriding configuration objects.</p><h3>The Rest Operator (...)</h3><p>The rest operator looks exactly like the spread operator, but its purpose is different.</p><p>While spread <strong>expands</strong> values,</p><p>rest <strong>collects</strong> multiple values into one.</p><h3>Rest in Destructuring</h3><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 24,<br>    city: &quot;Delhi&quot;<br>};<br>const { name, ...details } = user;</pre><p>Output:</p><pre>name<br>// Alice<br>details<br>// {<br>//     age: 24,<br>//     city: &quot;Delhi&quot;<br>// }</pre><p>Everything except name is collected into details.</p><h3>Rest Parameters</h3><p>Functions can also collect arguments.</p><pre>function sum(...numbers) {<br>console.log(numbers);<br>}<br>sum(1, 2, 3, 4);</pre><p>Output:</p><pre>[1, 2, 3, 4]</pre><p>Unlike the older arguments object, rest parameters produce a real array, making them easier to work with using methods like map(), filter(), and reduce().</p><h3>Optional Chaining (?.)</h3><p>Suppose we have:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};</pre><p>Now,</p><pre>console.log(user.address.city);</pre><p>throws:</p><pre>TypeError<br>Cannot read properties of undefined</pre><p>because address doesn&#39;t exist.</p><p>Optional chaining solves this elegantly.</p><pre>console.log(user.address?.city);</pre><p>Output:</p><pre>undefined</pre><p>Instead of throwing an error, JavaScript stops evaluating when it encounters null or undefined and returns undefined.</p><h3>Chaining Multiple Levels</h3><pre>const user = {<br>    profile: {<br>        address: {<br>            city: &quot;Delhi&quot;<br>        }<br>    }<br>};<br>console.log(user.profile?.address?.city);</pre><p>Output:</p><pre>Delhi</pre><p>Each ?. safely checks the previous value before continuing.</p><p>This feature is especially useful when working with API responses where certain properties may be missing.</p><h3>Nullish Coalescing (??)</h3><p>Developers often used the logical OR operator (||) to provide default values.</p><pre>const username = input || &quot;Guest&quot;;</pre><p>At first glance, this seems fine.</p><p>However, consider:</p><pre>const input = &quot;&quot;;<br>const username = input || &quot;Guest&quot;;<br>console.log(username);</pre><p>Output:</p><pre>Guest</pre><p>But what if an empty string is actually a valid value?</p><p>The logical OR operator treats <strong>all falsy values</strong> (0, &quot;&quot;, false, NaN, null, undefined) as missing.</p><p>The nullish coalescing operator behaves differently.</p><pre>const username = input ?? &quot;Guest&quot;;</pre><p>Now JavaScript only uses &quot;Guest&quot; when input is <strong>null</strong> or <strong>undefined</strong>.</p><p>Examples:</p><pre>0 ?? 100</pre><p>Output:</p><pre>0</pre><h3>Shallow Copy vs Deep Copy</h3><p>Let’s revisit object copying.</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    address: {<br>        city: &quot;Delhi&quot;<br>    }<br>};<br>const copy = {<br>    ...user<br>};</pre><p>At first glance, this looks like a complete copy.</p><p>However, it’s only a <strong>shallow copy</strong>.</p><p>Here’s why:</p><pre>copy.address.city = &quot;Mumbai&quot;;<br>console.log(user.address.city);</pre><p>Output:</p><pre>Mumbai</pre><p>Although copy is a new object, the nested address object is still shared between both objects.</p><p>Conceptually:</p><pre>user ──────────────┐<br>                   │<br>copy ──────────────┘<br>                   │<br>                   ▼<br>          address object</pre><p>The top-level object is copied, but nested objects remain shared.</p><p>A <strong>deep copy</strong> creates completely independent copies of every nested object as well.</p><p>Modern JavaScript provides structuredClone() for many deep-copy scenarios:</p><pre>const deepCopy = structuredClone(user);</pre><p>Now changes to nested objects inside deepCopy do not affect user.</p><p>Keep in mind that structuredClone() has some limitations (for example, it does not clone functions), but it&#39;s a much safer choice than older techniques like JSON.parse(JSON.stringify(...)) for many use cases.</p><h3>Loops and Array Iteration Methods</h3><p>JavaScript provides several ways to iterate over arrays and objects. Each loop serves a different purpose, and choosing the right one makes your code cleaner, more readable, and often more efficient.</p><h3>forEach()</h3><p>forEach() executes a callback function once for every element in an array.</p><p>Syntax:</p><pre>array.forEach(function(element, index, array) {<br>    // code to execute<br>});</pre><p>Example:</p><pre>const numbers = [10, 20, 30];<br>numbers.forEach((element, index) =&gt; {<br>    console.log(index, element);<br>});</pre><p>Output:</p><pre>0 10<br>1 20<br>2 30</pre><h3>Do We Need to Return Anything?</h3><p><strong>No.</strong></p><p>The return value of the callback is ignored.</p><pre>numbers.forEach(num =&gt; {<br>    return num * 2;<br>});</pre><p>Even though the callback returns a value, forEach() does nothing with it and always returns:</p><pre>undefined</pre><p>If you need a new array based on the existing one, use map() instead.</p><h3>Characteristics</h3><ul><li>Executes the callback for every element.</li><li>Cannot use break or continue.</li><li>Always iterates through the entire array.</li><li>Works only with arrays (and array-like structures that implement forEach()).</li><li>Slightly slower than a traditional for loop for very large datasets.</li><li>Does <strong>not</strong> return a new array.</li></ul><h3>for...of</h3><p>The for...of loop is used to iterate over <strong>iterable</strong> objects.</p><p>Examples of iterable objects include:</p><ul><li>Arrays</li><li>Strings</li><li>Maps</li><li>Sets</li><li>NodeLists</li><li>Generators</li></ul><p>Syntax:</p><pre>for (const element of iterable) {<br>    // code<br>}</pre><p>Example:</p><pre>const numbers = [10, 20, 30];<br>for (const number of numbers) {<br>    console.log(number);<br>}</pre><p>Output:</p><pre>10<br>20<br>30</pre><p>Notice that for...of iterates over <strong>values</strong>, not indexes.</p><h3>Getting Both Index and Value</h3><p>If you also need the index, use .entries().</p><pre>const numbers = [10, 20, 30];<br>for (const [index, value] of numbers.entries()) {<br>    console.log(index, value);<br>}</pre><p>Output:</p><pre>0 10<br>1 20<br>2 30</pre><h3>Characteristics</h3><ul><li>Iterates over values.</li><li>Supports break, continue, and return.</li><li>Cleaner syntax than a traditional for loop.</li><li>Doesn’t provide indexes directly.</li><li>Cannot iterate over plain objects.</li></ul><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>for (const value of user) {<br>}</pre><p>Output:</p><pre>TypeError: user is not iterable</pre><h3>for...in</h3><p>The for...in loop is used to iterate over an object&#39;s <strong>property names (keys)</strong>.</p><p>Syntax:</p><pre>for (const key in object) {<br>    // code<br>}</pre><p>Example:</p><pre>const user = {<br>    name: &quot;Alice&quot;,<br>    age: 25<br>};</pre><pre>for (const key in user) {<br>    console.log(key);<br>}</pre><p>Output:</p><pre>name<br>age</pre><h3>Using for...in with Arrays</h3><p>Although it works,</p><p>it is generally <strong>not recommended</strong>.</p><pre>const numbers = [10, 20, 30];<br>for (const index in numbers) {<br>    console.log(index);<br>}</pre><p>Output:</p><pre>0<br>1<br>2</pre><p>Notice that it iterates over the <strong>indexes</strong>, not the values.</p><p>This happens because arrays are internally objects whose property names are their indexes.</p><p>Conceptually:</p><pre>{<br>    &quot;0&quot;: 10,<br>    &quot;1&quot;: 20,<br>    &quot;2&quot;: 30<br>}</pre><p>If you need array values, prefer for...of.</p><h3>Inherited Properties</h3><p>for...in iterates over all <strong>enumerable</strong> properties, including inherited ones.</p><p>Example:</p><pre>const parent = {<br>    country: &quot;India&quot;<br>};<br>const user = Object.create(parent);<br>user.name = &quot;Alice&quot;;<br>for (const key in user) {<br>    console.log(key);<br>}</pre><p>Output:</p><pre>name<br>country</pre><p>If you only want the object’s own properties, combine it with:</p><pre>Object.hasOwn(user, key)</pre><p>or</p><pre>user.hasOwnProperty(key)</pre><h3>Characteristics</h3><ul><li>Iterates over property names (keys).</li><li>Includes inherited enumerable properties.</li><li>Ignores non-enumerable properties.</li><li>Not recommended for arrays.</li><li>Slightly slower than most array-specific iteration methods.</li></ul><h3>map()</h3><p>map() creates a <strong>new array</strong> by applying a callback function to every element.</p><p>Syntax:</p><pre>array.map((element, index, array) =&gt; mappedValue, thisArg);</pre><p>Example:</p><pre>const numbers = [1, 2, 3]<br>const doubled = numbers.map(num =&gt; num * 2);<br>console.log(doubled);</pre><p>Output:</p><pre>[<br>    2,<br>    4,<br>    6<br>]</pre><p>Unlike forEach(), the callback <strong>must return</strong> the value that should be placed in the new array.</p><h3>Characteristics</h3><ul><li>Returns a new array.</li><li>Original array remains unchanged.</li><li>Callback runs for every existing element.</li><li>Skips holes in sparse arrays.</li></ul><h3>filter()</h3><p>filter() creates a new array containing only the elements that satisfy a condition.</p><p>Syntax:</p><pre>array.filter((element, index, array) =&gt; boolean, thisArg);</pre><p>Example:</p><pre>const numbers = [1, 2, 3, 4, 5];<br>const even = numbers.filter(num =&gt; num % 2 === 0);<br>console.log(even);</pre><p>Output:</p><pre>[<br>    2,<br>    4<br>]</pre><p>Only elements for which the callback returns true are included in the result.</p><h3>Characteristics</h3><ul><li>Returns a new array</li><li>Does not modify the original array.</li><li>Callback must return true or false.</li><li>Skips holes in sparse arrays.</li></ul><h3>reduce()</h3><p>reduce() combines all elements of an array into a <strong>single value</strong>.</p><p>Syntax:</p><pre>array.reduce(<br>    (accumulator, element, index, array) =&gt; newAccumulator,<br>    initialValue<br>);</pre><p>Example:</p><pre>const numbers = [1, 2, 3, 4];<br>const sum = numbers.reduce(<br>    (accumulator, current) =&gt; accumulator + current,<br>    0<br>);<br>console.log(sum);</pre><p>Output:</p><pre>10</pre><p>The callback returns the updated accumulator after processing each element.</p><h3>Important Details</h3><p>If an initialValue is provided:</p><ul><li>The accumulator starts with that value.</li><li>The callback runs for every element.</li></ul><pre>numbers.reduce((acc, num) =&gt; acc + num, 0);</pre><p>If no initialValue is provided:</p><ul><li>The first element becomes the initial accumulator.</li><li>Iteration starts from index 1.</li></ul><pre>numbers.reduce((acc, num) =&gt; acc + num);</pre><p>If the array is empty and no initialValue is provided:</p><pre>TypeError</pre><h3>Characteristics</h3><ul><li>Returns a single value.</li><li>Processes elements from left to right.</li><li>Does not modify the original array.</li></ul><h3>reduceRight()</h3><p>reduceRight() works exactly like reduce(), except it processes elements from <strong>right to left</strong>.</p><p>Syntax:</p><pre>array.reduceRight(<br>    (accumulator, element) =&gt; newAccumulator,<br>    initialValue<br>);</pre><p>Example:</p><pre>const words = [&quot;JavaScript&quot;, &quot;is&quot;, &quot;awesome&quot;];<br>const sentence = words.reduceRight(<br>    (acc, word) =&gt; acc + &quot; &quot; + word<br>);<br>console.log(sentence);</pre><p>Output:</p><pre>awesome is JavaScript</pre><h3>Common Uses</h3><ul><li>Building strings in reverse order.</li><li>Processing nested structures from right to left.</li><li>Function composition.</li><li>Reverse reductions.</li></ul><h3>Part 9 — Functions: The Heart of JavaScript</h3><p>Functions allow us to group reusable pieces of code into a single unit.</p><p>Instead of writing the same code repeatedly, we define it once and call it whenever needed.</p><p>For example, imagine printing a greeting ten times.</p><p>Without functions:</p><pre>console.log(&quot;Welcome&quot;);<br>console.log(&quot;Welcome&quot;);<br>console.log(&quot;Welcome&quot;);<br>console.log(&quot;Welcome&quot;);<br>console.log(&quot;Welcome&quot;);</pre><p>This quickly becomes repetitive.</p><p>With functions:</p><pre>function greet() {<br>    console.log(&quot;Welcome&quot;);<br>}<br>greet();<br>greet();<br>greet();</pre><p>The code becomes shorter, cleaner, and easier to maintain.</p><h3>Function Declaration</h3><p>The most common way to define a function is with a function declaration.</p><pre>function multiply(a, b) {<br>return a * b;<br>}</pre><p>Function declarations are hoisted.</p><p>This means we can call them before they appear in the code.</p><pre>sayHello();<br>function sayHello() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><p>Output:</p><pre>Hello</pre><p>Why?</p><p>During the creation phase, JavaScript stores the entire function in memory.</p><h3>Function Expressions</h3><p>A <strong>function expression</strong> is a function that is created as part of an <strong>expression</strong>. The function can be assigned to a variable, passed as an argument, or returned from another function.</p><p>The most common form is assigning a function to a variable:</p><pre>const greet = function () {<br>  console.log(&quot;Hello&quot;);<br>};</pre><p>Here:</p><ul><li>function () { ... } is the <strong>function expression</strong>.</li><li>greet is the variable that stores a reference to the function.</li></ul><p>Unlike function declarations, <strong>function expressions are not fully hoisted</strong>. If the function expression is assigned to a variable declared with let or const, the variable is hoisted but remains in the <strong>Temporal Dead Zone (TDZ)</strong> until its declaration is executed.</p><p>Example</p><pre>greet();<br>const greet = function () {<br>  console.log(&quot;Hello&quot;);<br>};</pre><p><strong>Output:</strong></p><pre>ReferenceError: Cannot access &#39;greet&#39; before initialization</pre><p>This happens because:</p><ul><li>The variable greet is hoisted.</li><li>However, since it is declared with const, it stays in the <strong>Temporal Dead Zone (TDZ)</strong> until the declaration is reached.</li><li>The function expression is created and assigned to greet only when the assignment statement executes.</li></ul><blockquote><strong><em>Note:</em></strong><em> A function expression doesn’t have to be assigned to a variable. It can also be passed directly as an argument, returned from another function, or used immediately (IIFE).</em></blockquote><h3>Named Function Expression</h3><p>A function expression may also have its own name.</p><pre>const greet = function sayHello() {<br>console.log(&quot;Hello&quot;);<br>};</pre><p>Outside the function:</p><pre>sayHello();</pre><p>produces:</p><pre>ReferenceError</pre><p>The internal name sayHello exists only inside the function itself.</p><p>Named function expressions are mainly useful for debugging because the function name appears in stack traces.</p><h3>Anonymous Functions</h3><p>An <strong>anonymous function</strong> is a function that does <strong>not have an explicit name</strong> in its definition.</p><pre>const greet = function () {<br>  console.log(&quot;Hello&quot;);<br>};</pre><p>At first glance, the function above appears to be anonymous because it is declared without a name. However, in modern JavaScript, <strong>this function is not truly anonymous</strong>.</p><p>When an anonymous function is assigned to a variable, JavaScript <strong>infers the function’s name from the variable</strong>. As a result, the function’s name property becomes &quot;greet&quot;.</p><pre>const greet = function () {<br>  console.log(&quot;Hello&quot;);<br>};<br>console.log(greet.name); // &quot;greet&quot;</pre><p>A <strong>truly anonymous function</strong> has no name and an empty name property.</p><p>Example:</p><pre>console.log((function () {}).name); // &quot;&quot;</pre><p>Anonymous functions are commonly used as:</p><ul><li>Callback functions</li><li>Event handlers</li><li>Promise handlers</li><li>Array methods</li></ul><h3>Functions Are First-Class Citizens</h3><p>One of JavaScript’s defining characteristics is that functions are <strong>first-class citizens</strong> (or <strong>first-class functions</strong>).</p><p>This means functions can be treated like any other value.</p><p>They can be:</p><ul><li>Assigned to variables</li><li>Stored inside objects</li><li>Stored inside arrays</li><li>Passed to other functions</li><li>Returned from other functions</li></ul><p>This capability is the foundation of many advanced JavaScript patterns.</p><h3>Assigning Functions to Variables</h3><pre>const greet = function () {<br>console.log(&quot;Hello&quot;);<br>};<br>greet();</pre><p>Output:</p><pre>Hello</pre><p>The variable stores a reference to the function.</p><h3>Passing Functions as Arguments</h3><pre>function greet(name) {<br>console.log(&quot;Hello&quot;, name);<br>}<br>function processUser(callback) {<br>    callback(&quot;Alice&quot;);<br>}<br>processUser(greet);</pre><p>Output:</p><pre>Hello Alice</pre><p>Notice that we pass greet, not greet().</p><p>Passing greet gives the function itself.</p><p>Passing greet() would execute the function immediately and pass its return value instead.</p><h3>Returning Functions</h3><p>Functions can also create and return other functions.</p><pre>function createGreeter() {<br>return function () {<br>        console.log(&quot;Hello!&quot;);<br>    };<br>}<br>const greet = createGreeter();<br>greet();</pre><p>Output:</p><pre>Hello!</pre><p>This ability leads directly to one of JavaScript’s most powerful features: <strong>closures</strong>, which we’ll cover shortly.</p><h3>Higher-Order Functions</h3><p>A <strong>higher-order function</strong> is a function that can do <strong>one or both</strong> of the following:</p><ul><li>Accept another function as an argument (parameter).</li><li>Return another function as its result.</li></ul><p>Example:</p><pre>function calculate(a, b, operation) {<br>return operation(a, b);<br>}<br>function add(x, y) {<br>    return x + y;<br>}<br>console.log(calculate(10, 20, add));</pre><p>Output:</p><pre>30</pre><p>Here, calculate is a higher-order function because it receives another function.</p><h3>Callback Functions</h3><p>A callback is simply a function passed into another function to be executed later.</p><p>Example:</p><pre>function download(callback) {<br>console.log(&quot;Downloading...&quot;);<br>    callback();<br>}<br>download(function () {<br>    console.log(&quot;Download Complete&quot;);<br>});</pre><p>Output:</p><pre>Downloading...<br>Download Complete</pre><p>Callbacks are heavily used in:</p><ul><li>Event listeners</li><li>Timers</li><li>File handling</li><li>API requests</li><li>Array methods</li></ul><p>Historically, callbacks were the primary way to handle asynchronous operations before Promises and async/await became standard.</p><h3>Default Parameters</h3><p>Functions can define default values for parameters.</p><pre>function greet(name = &quot;Guest&quot;) {<br>console.log(&quot;Hello&quot;, name);<br>}<br>greet();</pre><p>Output:</p><pre>Hello Guest</pre><p>If an argument is provided:</p><pre>greet(&quot;Alice&quot;);</pre><p>Output:</p><pre>Hello Alice</pre><p>The default value is only used when the corresponding argument is undefined.</p><h3>Rest Parameters</h3><p>Suppose we want a function that accepts any number of arguments.</p><pre>function sum(...numbers) {<br>console.log(numbers);<br>}<br>sum(1, 2, 3, 4, 5);</pre><p>Output:</p><pre>[1, 2, 3, 4, 5]</pre><p>The rest parameter gathers all remaining arguments into an array.</p><p>Because it’s a real array, we can use array methods directly.</p><pre>function sum(...numbers) {<br>return numbers.reduce((total, value) =&gt; total + value, 0);<br>}<br>console.log(sum(10, 20, 30));</pre><p>Output:</p><pre>60</pre><h3>The arguments Object</h3><p>Before rest parameters existed, JavaScript provided the arguments object.</p><pre>function show() {<br>console.log(arguments);<br>}<br>show(10, 20, 30);</pre><p>Output:</p><pre>Arguments(3)<br>0: 10<br>1: 20<br>2: 30</pre><p>Although still available in regular functions, arguments is <strong>array-like</strong>, not a true array. It lacks methods such as map(), filter(), and reduce().</p><p>For modern JavaScript, rest parameters are generally preferred because they are clearer and provide a real array.</p><h3>Function Scope</h3><p>Every function creates its own scope.</p><p>Variables declared inside a function cannot be accessed from outside.</p><pre>function demo() {<br>let message = &quot;Hello&quot;;<br>}<br>console.log(message);</pre><p>Output:</p><pre>ReferenceError</pre><p>This encapsulation helps prevent accidental conflicts between variables in different parts of a program.</p><h3>Part 10 — Arrow Functions, Lexical Scope, Closures, IIFEs, and the Call Stack</h3><h3>Arrow Functions</h3><p>Consider a traditional function:</p><pre>function add(a, b) {<br>    return a + b;<br>}</pre><p>The same function can be written as an arrow function:</p><pre>const add = (a, b) =&gt; {<br>    return a + b;<br>};</pre><p>Both produce the same result.</p><pre>console.log(add(10, 20));</pre><p>Output:</p><pre>30</pre><p>At first glance, arrow functions seem like syntactic sugar.</p><p>However, they differ from regular functions in several important ways.</p><h3>Implicit Return</h3><p>If an arrow function contains only one expression, the return keyword can be omitted.</p><p>Traditional function:</p><pre>function square(x) {<br>    return x * x;<br>}</pre><p>Arrow function:</p><pre>const square = x =&gt; x * x;</pre><p>Both return:</p><pre>square(5);</pre><p>Output:</p><pre>25</pre><p>JavaScript automatically returns the result of the expression.</p><h3>Returning Objects</h3><p>One common mistake involves returning object literals.</p><p>This code does <strong>not</strong> work:</p><pre>const createUser = () =&gt; {<br>    name: &quot;Alice&quot;;<br>};</pre><p>Output:</p><pre>undefined</pre><p>Why?</p><p>JavaScript interprets the curly braces as the function body rather than an object.</p><p>To return an object directly, wrap it in parentheses.</p><pre>const createUser = () =&gt; ({<br>    name: &quot;Alice&quot;<br>});</pre><p>Now the output is:</p><pre>{<br>    name: &quot;Alice&quot;<br>}</pre><h3>Arrow Functions and the this Keyword</h3><p>This is where arrow functions become fundamentally different.</p><p>Regular functions create their own this.</p><p>Arrow functions do <strong>not</strong>.</p><p>Instead, they inherit this from the surrounding lexical scope.</p><p>Consider:</p><pre>const user = {<br>name: &quot;Alice&quot;,<br>    greet() {<br>        console.log(this.name);<br>    }<br>};<br>user.greet();</pre><p>Output:</p><pre>Alice</pre><p>Here,</p><pre>this</pre><p>refers to user.</p><p>Now compare:</p><pre>const user = {name: &quot;Alice&quot;,<br>    greet: () =&gt; {<br>        console.log(this.name);<br>    }<br>};<br>user.greet();</pre><p>Output (in a browser):</p><pre>undefined</pre><p>Why?</p><p>Because the arrow function never creates its own this.</p><p>Instead, it inherits this from the surrounding scope, which in this case is the global scope.</p><p>Since:</p><pre>window.name</pre><p>is usually undefined (or an unrelated value), the output isn’t &quot;Alice&quot;.</p><p>This is one of the biggest reasons why arrow functions should <strong>not</strong> generally be used as object methods.</p><p>Arrow functions shine in callbacks, array methods, and situations where you intentionally want to preserve the surrounding this.</p><h3>Lexical Scope</h3><p>Before understanding closures, we need to understand <strong>lexical scope</strong>.</p><p>The word <strong>lexical</strong> means:</p><blockquote><em>“Determined by where code is written.”</em></blockquote><p>Consider:</p><pre>const language = &quot;JavaScript&quot;;<br>function outer() {<br>    function inner() {<br>        console.log(language);<br>    }<br>    inner();<br>}<br>outer();</pre><p>Output:</p><pre>JavaScript</pre><p>How did inner() access language?</p><p>JavaScript searches for variables in this order:</p><ol><li>Current scope.</li><li>Parent scope.</li><li>Grandparent scope.</li><li>Continue until the global scope.</li><li>If nothing is found, throw a ReferenceError.</li></ol><p>This searching process is called the <strong>scope chain</strong>.</p><h3>Visualizing the Scope Chain</h3><pre>Global Scope</pre><pre>language</pre><pre>│</pre><pre>▼</pre><pre>outer()</pre><pre>│</pre><pre>▼</pre><pre>inner()</pre><p>When inner() needs language, JavaScript climbs the scope chain until it finds it.</p><p>Notice that the search only moves <strong>outward</strong>.</p><p>Parent scopes cannot access variables declared inside child scopes.</p><h3>Closures</h3><p>Closures are one of JavaScript’s most powerful and frequently misunderstood concepts.</p><p>A closure is created whenever a function remembers variables from its lexical scope, even after that outer function has finished executing.</p><p>Consider this example:</p><pre>function outer() {<br><br>    let count = 0;<br><br>    function inner() {<br><br>        count++;<br><br>        console.log(count);<br><br>    }<br><br>    return inner;<br><br>}<br><br>const counter = outer();<br><br>counter();<br><br>counter();<br><br>counter();</pre><p>Output:</p><pre>1<br>2<br>3</pre><p>At first glance, this seems impossible.</p><p>outer() has already finished executing.</p><p>Shouldn’t count have been destroyed?</p><p>The answer is <strong>no</strong>.</p><h3>Why Does This Work?</h3><p>When outer() finishes, JavaScript notices that inner() still references count.</p><p>Instead of destroying count, JavaScript keeps it alive because the returned function still needs it.</p><p>Conceptually:</p><pre>outer()<br><br>↓<br><br>count = 0<br><br>↓<br><br>return inner<br><br>↓<br><br>outer() finishes<br><br>↓<br><br>count remains alive<br><br>↓<br><br>counter()<br><br>↓<br><br>count = 1<br><br>↓<br><br>counter()<br><br>↓<br><br>count = 2</pre><p>The function carries its surrounding environment with it.</p><p>That preserved environment is called a <strong>closure</strong>.</p><h3>Closures in Event Listeners</h3><p>Closures are heavily used by browsers.</p><pre>function setupButton() {<br>let clicks = 0;<br>    button.addEventListener(&quot;click&quot;, function () {<br>        clicks++;<br>        console.log(clicks);<br>    });<br>}</pre><p>Every time the button is clicked, the callback remembers the clicks variable.</p><p>Even though setupButton() has already finished, the callback still has access to its lexical environment.</p><p>This is a practical example of closures in action.</p><h3>Immediately Invoked Function Expressions (IIFEs)</h3><p>Sometimes we want a function to execute immediately after it’s defined.</p><p>That’s exactly what an <strong>Immediately Invoked Function Expression</strong>, or <strong>IIFE</strong>, does.</p><pre>(function () {console.log(&quot;Runs immediately&quot;);<br>})();</pre><p>Output:</p><pre>Runs immediately</pre><p>The function is:</p><ol><li>Defined.</li><li>Executed immediately.</li><li>Never called again.</li></ol><h3>Why Were IIFEs Popular?</h3><p>Before ES6 introduced block-scoped variables (let and const), JavaScript only had function scope.</p><p>Developers used IIFEs to create isolated scopes and avoid polluting the global namespace.</p><p>Example:</p><pre>(function () {<br>var secret = &quot;Hidden&quot;;<br>    console.log(secret);<br>})();</pre><p>Output:</p><pre>Hidden</pre><p>Outside the IIFE:</p><pre>console.log(secret);</pre><p>Output:</p><pre>ReferenceError</pre><p>Today, let, const, and ES modules have largely replaced many use cases for IIFEs, but you&#39;ll still encounter them in older codebases and libraries.</p><h3>The Call Stack</h3><p>Every time a function is called, JavaScript creates a new execution context and pushes it onto the <strong>call stack</strong>.</p><p>Consider:</p><pre>function one() {<br>two();<br>}<br>function two() {<br>    three();<br>}<br>function three() {<br>    console.log(&quot;Done&quot;);<br>}<br>one();</pre><p>The call stack grows like this:</p><pre>Start<br>↓<br>one()<br>↓<br>two()<br>↓<br>three()<br>↓<br>console.log()<br>↓<br>Done<br>↓<br>three() removed<br>↓<br>two() removed<br>↓<br>one() removed<br>↓<br>Stack Empty</pre><p>The stack always follows the <strong>Last In, First Out (LIFO)</strong> principle.</p><p>The last function added is the first one removed.</p><h3>Stack Overflow</h3><p>What happens if functions keep calling themselves forever?</p><pre>function test() {<br>test();<br>}<br>test();</pre><p>Eventually, JavaScript runs out of stack space and throws:</p><pre>RangeError:<br>Maximum call stack size exceeded</pre><p>Every recursive function must eventually stop; otherwise, the call stack continues to grow until it overflows.</p><h3>Part 11 — JavaScript Runtime, Event Loop, Web APIs, Microtasks, and Macrotasks</h3><p>One of the biggest misconceptions about JavaScript is:</p><blockquote><em>JavaScript can do multiple things simultaneously.</em></blockquote><p>Not exactly.</p><p>JavaScript is <strong>single-threaded</strong>.</p><p>That means it has only <strong>one call stack</strong> and executes one piece of JavaScript code at a time.</p><p>So how can it:</p><ul><li>Download files</li><li>Make API calls</li><li>Handle button clicks</li><li>Play videos</li><li>Listen for keyboard events</li><li>Run timers</li></ul><p>without blocking everything else?</p><p>To answer that, we first need to understand what JavaScript actually is — and what it isn’t.</p><h3>JavaScript Is Just the Language</h3><p>Many beginners think JavaScript itself provides features like:</p><ul><li>setTimeout()</li><li>fetch()</li><li>document</li><li>window</li><li>console.log()</li></ul><p>It doesn’t.</p><p>These are <strong>not part of the JavaScript language</strong>.</p><p>They are provided by the <strong>runtime environment</strong>.</p><p>For example:</p><p>In a browser:</p><pre>JavaScript Engine<br>+<br>Browser Runtime<br>↓<br>Window<br>↓<br>Document<br>↓<br>DOM<br>↓<br>Fetch<br>↓<br>setTimeout<br>↓<br>WebSocket<br>↓<br>LocalStorage</pre><p>In Node.js:</p><pre>JavaScript Engine<br>+<br>Node.js Runtime<br>↓<br>File System<br>↓<br>HTTP Module<br>↓<br>Process<br>↓<br>Streams<br>↓<br>Timers</pre><p>JavaScript itself knows nothing about browsers.</p><p>It only knows how to execute JavaScript code.</p><p>Everything else comes from the runtime.</p><h3>The JavaScript Runtime</h3><p>When JavaScript runs inside a browser, several components work together.</p><pre>───────<br>Browser Runtime<br>───────────────────────────────<br>Call Stack<br>↓<br>Heap Memory<br>↓<br>Web APIs<br>↓<br>Callback Queue<br>↓<br>Microtask Queue<br>↓<br>Event Loop<br>───────────────────────────────</pre><p>Every asynchronous operation passes through these components.</p><p>Let’s understand each one.</p><h3>The Call Stack</h3><p>You’ve already seen the call stack in the previous chapter.</p><p>Whenever JavaScript calls a function, it pushes that function onto the stack.</p><p>Example:</p><pre>function first() {<br>    second();<br>}<br>function second() {<br>    third();<br>}<br>function third() {<br>    console.log(&quot;Done&quot;);<br>}<br>first();</pre><p>The stack grows like this:</p><pre>first()<br>↓<br>second()<br>↓<br>third()<br>↓<br>console.log()<br>↓<br>Done<br>↓<br>console.log removed<br>↓<br>third removed<br>↓<br>second removed<br>↓<br>first removed</pre><p>Only one function executes at a time.</p><p>This is why JavaScript is single-threaded.</p><h3>Blocking the Call Stack</h3><p>Imagine this code:</p><pre>function wait() {<br>while (true) {}<br>}<br>wait();<br>console.log(&quot;Hello&quot;);</pre><p>Will &quot;Hello&quot; ever print?</p><p>No.</p><p>The infinite loop never leaves the call stack.</p><p>Since the stack never becomes empty,</p><pre>console.log(&quot;Hello&quot;);</pre><p>never gets a chance to execute.</p><p>This is called <strong>blocking the main thread</strong>.</p><h3>Why Asynchronous Programming Exists</h3><p>Imagine downloading a 5 GB file.</p><p>If JavaScript had to wait,</p><pre>downloadLargeFile();<br>console.log(&quot;Finished&quot;);</pre><p>the browser would freeze for several minutes.</p><p>No scrolling.</p><p>No clicks.</p><p>No animations.</p><p>Nothing.</p><p>Instead,</p><p>JavaScript delegates long-running tasks to the browser.</p><h3>Web APIs</h3><p>Browsers provide special features called <strong>Web APIs</strong>.</p><p>These APIs operate independently of the JavaScript engine.</p><p>Examples include:</p><ul><li>setTimeout()</li><li>setInterval()</li><li>fetch()</li><li>DOM Events</li><li>addEventListener()</li><li>WebSocket</li><li>Geolocation</li><li>MutationObserver</li></ul><p>When JavaScript calls one of these APIs, it hands the task over to the browser and immediately continues executing the next line.</p><h3>Understanding setTimeout</h3><p>Consider:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(function () {<br>    console.log(&quot;Timer&quot;);<br>}, 2000);<br>console.log(&quot;End&quot;);</pre><p>Many beginners expect:</p><pre>Start<br>(wait 2 seconds)<br>Timer<br>End</pre><p>But the actual output is:</p><pre>Start<br>End<br>(wait 2 seconds)<br>Timer</pre><p>Let’s see why.</p><h3>Step-by-Step Execution</h3><p>Initially,</p><pre>Call Stack<br>↓<br>console.log(&quot;Start&quot;)</pre><p>prints:</p><pre>Start</pre><p>Next,</p><p>JavaScript encounters:</p><pre>setTimeout(...)</pre><p>Does JavaScript wait?</p><p>No.</p><p>Instead,</p><pre>Call Stack<br>↓<br>setTimeout()<br>↓<br>Browser Web API</pre><p>The browser starts a 2-second timer.</p><p>Meanwhile,</p><p>JavaScript immediately continues.</p><pre>console.log(&quot;End&quot;);</pre><p>prints:</p><pre>End</pre><p>Only after:</p><ul><li>the timer finishes,</li><li>and the call stack becomes empty,</li></ul><p>does the callback move into the callback queue.</p><h3>Callback Queue (Macrotask Queue)</h3><p>When an asynchronous task finishes, its callback doesn’t execute immediately.</p><p>Instead, it waits inside the <strong>callback queue</strong>.</p><p>Example:</p><pre>Call Stack<br>↓<br>(empty)<br>Callback Queue<br>↓<br>Timer Callback</pre><p>The callback remains there until the Event Loop moves it onto the call stack.</p><h3>The Event Loop</h3><p>The Event Loop is surprisingly simple.</p><p>Its job is:</p><pre>Forever:<br>↓<br>Is Call Stack Empty?<br>↓<br>YES<br>↓<br>Take first callback<br>↓<br>Push onto Call Stack<br>↓<br>Repeat</pre><p>That’s all.</p><p>The Event Loop doesn’t execute your code.</p><p>It simply moves callbacks from queues onto the call stack when JavaScript is ready.</p><h3>Visualizing setTimeout</h3><pre>console.log(&quot;A&quot;);<br>setTimeout(() =&gt; {<br>    console.log(&quot;B&quot;);<br>}, 1000);<br>console.log(&quot;C&quot;);</pre><p>Execution:</p><pre>Call Stack<br>↓<br>A<br>↓<br>setTimeout<br>↓<br>Browser Timer<br>↓<br>C<br>↓<br>Call Stack Empty<br>↓<br>1 second passes<br>↓<br>Callback Queue<br>↓<br>Event Loop<br>↓<br>Call Stack<br>↓<br>B</pre><p>Final Output:</p><pre>A<br>C<br>B</pre><h3>Does setTimeout(fn, 0) Execute Immediately?</h3><p>A common interview question is:</p><pre>setTimeout(() =&gt; {<br>console.log(&quot;Hello&quot;);<br>}, 0);<br>console.log(&quot;World&quot;);</pre><p>Many people think:</p><pre>Hello<br>World</pre><p>But the actual output is:</p><pre>World<br>Hello</pre><p>Why?</p><p>Because even with a delay of 0, the callback still goes through the Web API, then into the callback queue, and only executes after the current call stack is empty.</p><p>A delay of 0 means &quot;schedule this as soon as possible,&quot; not &quot;run it immediately.&quot;</p><h3>Promises Behave Differently</h3><p>Now consider:</p><pre>console.log(&quot;Start&quot;);<br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;Promise&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p>Output:</p><pre>Start<br>End<br>Promise</pre><p>That seems similar to setTimeout().</p><p>Now compare:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; {<br>    console.log(&quot;Timeout&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;Promise&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p>Many developers expect:</p><pre>Start<br>End<br>Timeout<br>Promise</pre><p>But the actual output is:</p><pre>Start<br>End<br>Promise<br>Timeout</pre><p>Why?</p><p>Because Promises use a different queue.</p><h3>Microtask Queue vs Macrotask Queue</h3><p>The browser maintains two important queues.</p><pre>Microtask Queue<br>↓<br>Promise.then()<br>queueMicrotask()<br>MutationObserver()<br>────────────────────────<br>Macrotask Queue<br>↓<br>setTimeout()<br>setInterval()<br>DOM Events<br>MessageChannel</pre><p>The Event Loop always processes:</p><pre>Current Call Stack<br>↓<br>ALL Microtasks<br>↓<br>ONE Macrotask<br>↓<br>Repeat</pre><p>Microtasks always have higher priority.</p><h3>Visualizing Queue Priority</h3><p>Suppose:</p><pre>console.log(&quot;A&quot;);<br>setTimeout(() =&gt; console.log(&quot;B&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));<br>console.log(&quot;D&quot;);</pre><p>Execution:</p><pre>Stack<br>↓<br>A<br>↓<br>setTimeout<br>↓<br>Promise<br>↓<br>D<br>↓<br>Stack Empty<br>↓<br>Microtask Queue<br>↓<br>C<br>↓<br>Macrotask Queue<br>↓<br>B</pre><p>Output:</p><pre>A<br>D<br>C<br>B</pre><h3>Multiple Promises</h3><pre>console.log(&quot;Start&quot;);<br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;One&quot;);<br>});<br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;Two&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p>Output:</p><pre>Start<br>End<br>One<br>Two</pre><p>Microtasks execute in the order they were queued.</p><h3>Multiple Timers</h3><pre>setTimeout(() =&gt; {<br>console.log(1);<br>}, 0);<br>setTimeout(() =&gt; {<br>    console.log(2);<br>}, 0);</pre><p>Output:</p><pre>1<br></pre><p>Macrotasks are also processed in FIFO (First In, First Out) order.</p><h3>A Common Interview Question</h3><p>Predict the output:</p><pre>console.log(&quot;1&quot;);<br>setTimeout(() =&gt; console.log(&quot;2&quot;), 0);<br>Promise.resolve().then(() =&gt; console.log(&quot;3&quot;));<br>console.log(&quot;4&quot;);</pre><p>Think before looking at the answer.</p><p>Execution:</p><ol><li>&quot;1&quot; is printed.</li><li>setTimeout schedules a macrotask.</li><li>Promise.then schedules a microtask.</li><li>&quot;4&quot; is printed.</li><li>The call stack becomes empty.</li><li>All microtasks are processed.</li><li>Then the first macrotask is processed.</li></ol><p>Final output:</p><pre>1<br>4<br>3<br>2</pre><h3>Part 12 — Promises, Async/Await, and Modern Asynchronous JavaScript</h3><h3>Why Are Callbacks Important?</h3><p>Callbacks are one of the main reasons <strong>asynchronous programming</strong> is possible in JavaScript.</p><p>Instead of waiting for a task to finish, JavaScript can continue executing the remaining code while providing a callback function that will be executed later when the task is complete.</p><p>For example:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; {<br>    console.log(&quot;Task Completed&quot;);<br>}, 2000);<br>console.log(&quot;End&quot;);</pre><p>Output:</p><pre>Start<br>End<br>Task Completed</pre><p>Here, JavaScript doesn’t wait for setTimeout() to finish. Instead, it registers the callback and continues executing the remaining synchronous code. Once the timer expires, the callback is executed.</p><h3>Problems with Callbacks</h3><p>Although callbacks made asynchronous programming possible, they introduced several problems.</p><p>The two biggest problems are:</p><ul><li>Callback Hell</li><li>Inversion of Control</li></ul><h3>Callback Hell (Pyramid of Doom)</h3><p>When one asynchronous operation depends on another, callbacks become nested inside each other.</p><p>As more operations are added, the code starts growing horizontally, making it difficult to read, debug, and maintain.</p><p>This is known as <strong>Callback Hell</strong> or the <strong>Pyramid of Doom</strong>.</p><p>Example:</p><pre>f1((err1, result1) =&gt; {<br>if (err1) return handle(err1);<br>    f2((err2, result2) =&gt; {<br>        if (err2) return handle(err2);<br>        f3((err3, result3) =&gt; {<br>            if (err3) return handle(err3);<br>            console.log(&quot;Done&quot;);<br>        });<br>    });<br>});</pre><p>As the number of asynchronous tasks increases, the nesting keeps increasing, making the code harder to understand.</p><h3>Inversion of Control</h3><p>Another major problem with callbacks is <strong>Inversion of Control</strong>.</p><p>When you pass your callback to another function, you are trusting that function to execute your callback correctly.</p><p>You lose control over your own code.</p><p>The function receiving your callback might:</p><ul><li>Never call it.</li><li>Call it multiple times.</li><li>Call it too early.</li><li>Call it too late.</li><li>Call it with incorrect arguments.</li><li>Throw an error before calling it.</li></ul><h3>Example 1</h3><pre>function doWork(callback) {<br>return true;<br>}</pre><p>Here, the callback is <strong>never executed</strong>.</p><h3>Example 2</h3><pre>function doWork(callback) {<br>callback();<br>    callback();<br>}</pre><p>Here, the callback is executed <strong>twice</strong>, which may cause unexpected behavior.</p><p>This uncertainty is called <strong>Inversion of Control</strong> because you no longer control when or how your callback is executed.</p><h3>Callback Error Handling</h3><p>Callbacks usually follow the <strong>Error-First Callback</strong> pattern.</p><p>The first argument is reserved for an error.</p><p>If an error occurs, it contains the error object.</p><p>Otherwise, it is null.</p><p>Example:</p><pre>function completeTask(callback) {<br>if (complete) {<br>        callback(null, completedWork);<br>    } else {<br>        callback(error, null);<br>    }<br>}</pre><p>Using the function:</p><pre>completeTask(function(err, result) {<br>if (err) {<br>        console.log(&quot;Task Failed&quot;);<br>    } else {<br>        console.log(result);<br>    }<br>});</pre><p>This pattern became the standard way of handling asynchronous operations in Node.js before Promises were introduced.</p><h3>Why Can’t We Use try...catch?</h3><p>One of the biggest drawbacks of callbacks is that <strong>try...catch cannot catch errors thrown asynchronously.</strong></p><p>try...catch only works for:</p><ul><li>Synchronous code</li><li>Errors thrown immediately while the current code is executing</li></ul><p>Example:</p><pre>try {<br>setTimeout(() =&gt; {<br>        throw new Error(&quot;Something went wrong&quot;);<br>    }, 1000);<br>} catch (err) {<br>    console.log(&quot;Caught&quot;);<br>}</pre><p>Output:</p><pre>Uncaught Error: Something went wrong</pre><p>Why?</p><p>Because the callback runs <strong>later</strong>, after the current call stack has already finished executing.</p><p>When the error is thrown, the try...catch block is no longer active.</p><p>For this reason, callback-based code usually handles errors using the first callback parameter (err) instead of relying on try...catch.</p><h3>Summary</h3><p>Callbacks made asynchronous programming possible by allowing JavaScript to continue executing other code while scheduling a function to run later.</p><p>However, callbacks introduced several challenges:</p><ul><li>Deeply nested callbacks lead to <strong>Callback Hell (Pyramid of Doom)</strong>.</li><li>Passing callbacks to other functions causes <strong>Inversion of Control</strong>, where you no longer control when or how your callback is executed.</li><li>Error handling becomes more difficult because try...catch does not work with asynchronous callbacks.</li></ul><p>These limitations eventually led to the introduction of <strong>Promises</strong> and later <strong>async/</strong><strong>await</strong>, which provide a cleaner and more reliable way to write asynchronous code.</p><h3>Why Do We Need Promises?</h3><p>Suppose we need to perform three asynchronous operations:</p><ol><li>Download user information.</li><li>Download the user’s posts.</li><li>Download comments for those posts.</li></ol><p>Using callbacks:</p><pre>getUser(function (user) {<br>getPosts(user.id, function (posts) {<br>        getComments(posts[0].id, function (comments) {<br>            console.log(comments);<br>        });<br>    });<br>});</pre><p>Notice how each callback is nested inside another.</p><p>As more operations are added, the code keeps shifting to the right.</p><p>This pattern is known as <strong>Callback Hell</strong> or the <strong>Pyramid of Doom</strong>.</p><p>It becomes difficult to:</p><ul><li>Read</li><li>Debug</li><li>Handle errors</li><li>Reuse code</li></ul><p>Promises solve this problem.</p><h3>What Is a Promise?</h3><p>A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.</p><p>Think of it as a placeholder for a value that may not be available yet.</p><p>Instead of returning the final value immediately, an asynchronous function returns a Promise.</p><p>When the operation finishes, the Promise is resolved or rejected.</p><h3>Promise States</h3><p>Every Promise is always in one of three states.</p><h3>Pending</h3><p>The operation is still running.</p><p>Example:</p><p>Downloading a file.</p><h3>Fulfilled</h3><p>The operation completed successfully.</p><p>Example:</p><p>The API returned user data.</p><h3>Rejected</h3><p>The operation failed.</p><p>Example:</p><p>Network error.</p><p>Server unavailable.</p><p>Permission denied.</p><p>Once a Promise becomes fulfilled or rejected, its state is final and cannot change again.</p><h3>Creating a Promise</h3><p>A Promise is created using the Promise constructor.</p><pre>const promise = new Promise((resolve, reject) =&gt; {<br>const success = true;<br>    if (success) {<br>        resolve(&quot;Operation Successful&quot;);<br>    } else {<br>        reject(&quot;Something went wrong&quot;);<br>    }<br>});</pre><p>The constructor receives a function called the <strong>executor</strong>.</p><p>The executor receives two functions:</p><ul><li>resolve</li><li>reject</li></ul><p>Calling resolve() fulfills the Promise.</p><p>Calling reject() rejects it.</p><h3>Consuming a Promise</h3><p>We use .then() to receive successful results.</p><pre>promise.then(result =&gt; {<br>console.log(result);<br>});</pre><p>Output:</p><pre>Operation Successful</pre><p>If the Promise fails,</p><p>we use .catch().</p><pre>promise.catch(error =&gt; {console.log(error);<br>});</pre><p>Output:</p><pre>Something went wrong</pre><h3>Promise Chaining</h3><p>Suppose we have multiple asynchronous operations.</p><p>Instead of nesting callbacks,</p><p>Promises allow chaining.</p><pre>getUser()<br>.then(user =&gt; {<br>    return getPosts(user.id);<br>})<br>.then(posts =&gt; {<br>    return getComments(posts[0].id);<br>})<br>.then(comments =&gt; {<br>    console.log(comments);<br>})<br>.catch(error =&gt; {<br>    console.log(error);<br>});</pre><p>Each .then() waits for the previous Promise to complete.</p><p>This creates code that is much flatter and easier to follow.</p><h3>Returning Values from .then()</h3><p>Consider:</p><pre>Promise.resolve(10)<br>.then(value =&gt; {<br>    return value * 2;<br>})<br>.then(value =&gt; {<br>    console.log(value);<br>});</pre><p>Output:</p><pre>20</pre><p>Whatever you return from a .then() becomes the input to the next .then().</p><h3>Returning Another Promise</h3><p>A .then() callback can also return another Promise.</p><pre>fetchUser()<br>.then(user =&gt; {<br>    return fetchPosts(user.id);<br>})<br>.then(posts =&gt; {<br>    console.log(posts);<br>});</pre><p>JavaScript automatically waits for the returned Promise to settle before continuing the chain.</p><p>This behavior is what makes Promise chaining so powerful.</p><h3>Error Propagation</h3><p>Suppose:</p><pre>Promise.resolve()<br>.then(() =&gt; {<br>    throw new Error(&quot;Failure&quot;);<br>})<br>.catch(error =&gt; {<br>    console.log(error.message);<br>});</pre><p>Output:</p><pre>Failure</pre><p>Throwing an error inside a .then() automatically rejects the Promise, allowing .catch() to handle it.</p><h3>The .finally() Method</h3><p>Sometimes you want code to run regardless of whether the Promise succeeds or fails.</p><p>For example:</p><ul><li>Stop a loading spinner.</li><li>Close a database connection.</li><li>Hide a loading animation.</li></ul><p>That’s what .finally() is for.</p><pre>fetchData()<br>.then(data =&gt; {<br>    console.log(data);<br>})<br>.catch(error =&gt; {<br>    console.log(error);<br>})<br>.finally(() =&gt; {<br>    console.log(&quot;Finished&quot;);<br>});</pre><p>The callback passed to .finally() runs whether the Promise is fulfilled or rejected.</p><h3>Promise.all()</h3><p>Suppose we need several independent API requests.</p><p>Without Promise.all():</p><pre>const users = await fetchUsers();<br>const posts = await fetchPosts();<br>const comments = await fetchComments();</pre><p>Each request waits for the previous one to finish.</p><p>If they are independent, this wastes time.</p><p>Instead:</p><pre>Promise.all([fetchUsers(),<br>    fetchPosts(),<br>    fetchComments()<br>])<br>.then(results =&gt; {<br>    console.log(results);<br>});</pre><p>All requests start simultaneously.</p><p>The Promise resolves only after <strong>every Promise succeeds</strong>.</p><h3>What Happens if One Promise Fails?</h3><pre>Promise.all([Promise.resolve(1),<br>    Promise.reject(&quot;Error&quot;),<br>    Promise.resolve(3)<br>])<br>.catch(console.log);</pre><p>Output:</p><pre>Error</pre><p>The entire Promise.all() rejects immediately when any Promise rejects.</p><h3>Promise.allSettled()</h3><p>Sometimes you want results from every Promise, even if some fail.</p><pre>Promise.allSettled([Promise.resolve(1),<br>    Promise.reject(&quot;Failed&quot;),<br>    Promise.resolve(3)<br>])<br>.then(console.log);</pre><p>Output:</p><pre>[<br>    { status: &quot;fulfilled&quot;, value: 1 },<br>{ status: &quot;rejected&quot;, reason: &quot;Failed&quot; },<br>    { status: &quot;fulfilled&quot;, value: 3 }<br>]</pre><p>Unlike Promise.all(), no Promise is ignored.</p><h3>Promise.race()</h3><p>Promise.race() returns the first Promise that settles.</p><pre>Promise.race([fetchFromServerA(),<br>    fetchFromServerB()<br>]);</pre><p>Whichever server responds first wins.</p><p>The others are ignored.</p><p>This is useful for implementing request timeouts or using multiple servers.</p><h3>Promise.any()</h3><p>Promise.any() resolves with the first fulfilled Promise.</p><p>Rejected Promises are ignored unless every Promise rejects.</p><pre>Promise.any([<br>Promise.reject(),<br>    Promise.resolve(&quot;Success&quot;),<br>    Promise.resolve(&quot;Another&quot;)<br>])<br>.then(console.log);</pre><p>Output:</p><pre>Success</pre><h3>Async Functions</h3><p>Promises improved asynchronous code.</p><p>async/await made it even cleaner.</p><p>An async function automatically returns a Promise.</p><pre>async function greet() {<br>return &quot;Hello&quot;;<br>}</pre><p>This is equivalent to:</p><pre>function greet() {<br>return Promise.resolve(&quot;Hello&quot;);<br>}</pre><h3>The await Keyword</h3><p>Inside an async function,</p><p>await pauses the function until a Promise settles.</p><pre>async function getUser() {<br>const response = await fetch(&quot;/users&quot;);<br>    const data = await response.json();<br>    console.log(data);<br>}</pre><p>Notice how this resembles synchronous code, even though it performs asynchronous operations.</p><p>Importantly, await pauses only the async function—not the entire JavaScript engine.</p><h3>Error Handling with try...catch</h3><p>Instead of .catch(),</p><p>async/await commonly uses try...catch.</p><pre>async function loadUser() {<br>try {<br>        const user = await fetchUser();<br>        console.log(user);<br>    } catch (error) {<br>        console.log(error);<br>    }<br>}</pre><p>This style is often easier to read, especially when dealing with multiple asynchronous operations.</p><h3>Sequential vs Parallel await</h3><p>Consider:</p><pre>const user = await fetchUser();<br>const posts = await fetchPosts();</pre><p>These execute one after the other.</p><p>If the requests are independent, a faster approach is:</p><pre>const [user, posts] = await Promise.all([<br>fetchUser(),<br>    fetchPosts()<br>]);</pre><p>Both requests start at the same time, reducing the total waiting time.</p><p>This is a common performance optimization in modern JavaScript.</p><h3>Promise Resolution Procedure (Promise Flattening / Unwrapping)</h3><p>When working with Promises, JavaScript automatically handles the values you return from .then() callbacks.</p><p>This behavior is known as the <strong>Promise Resolution Procedure</strong>, also called <strong>Promise Flattening</strong> or <strong>Promise Unwrapping</strong>.</p><p>It allows promise chains to remain clean without manually wrapping everything in Promise.resolve().</p><h3>Returning a Normal Value</h3><p>If you return a normal value from a .then() callback, JavaScript automatically wraps it inside a <strong>resolved Promise</strong>.</p><p>Example:</p><pre>Promise.resolve(10)<br>    .then(value =&gt; {<br>        return value * 2;<br>    })<br>    .then(result =&gt; {<br>        console.log(result);<br>    });</pre><p>Output:</p><pre>20</pre><p>Internally, JavaScript treats it like:</p><pre>Promise.resolve(value * 2);</pre><p>So these are equivalent:</p><pre>.then(() =&gt; {<br>    return 20;<br>})<br><br>.then(() =&gt; {<br>    return Promise.resolve(20);<br>})</pre><h3>Returning Another Promise</h3><p>If you return another Promise, JavaScript automatically waits for that Promise to settle before continuing the chain.</p><p>Example:</p><pre>Promise.resolve(10)<br>    .then(value =&gt; {<br>        return Promise.resolve(value * 2);<br>    })<br>    .then(result =&gt; {<br>        console.log(result);<br>    });</pre><p>Output:</p><pre>20</pre><p>JavaScript automatically <strong>unwraps</strong> the returned Promise instead of creating a nested Promise.</p><p>Without this behavior, we’d end up with:</p><pre>Promise&lt;Promise&lt;number&gt;&gt;</pre><p>Instead, JavaScript automatically flattens it into:</p><pre>Promise&lt;number&gt;</pre><p>This automatic waiting is called <strong>Promise Flattening</strong> or <strong>Promise Unwrapping</strong>.</p><h3>Throwing an Error</h3><p>If you throw an error inside a .then() callback, JavaScript automatically converts it into a <strong>rejected Promise</strong>.</p><p>Example:</p><pre>Promise.resolve(10)<br>    .then(() =&gt; {<br>        throw new Error(&quot;Something went wrong&quot;);<br>    })<br>    .catch(err =&gt; {<br>        console.log(err.message);<br>    });</pre><p>Output:</p><pre>Something went wrong</pre><p>Internally, JavaScript behaves as if you had written:</p><pre>return Promise.reject(new Error(&quot;Something went wrong&quot;));</pre><p>So these are equivalent:</p><pre>throw new Error(&quot;Error&quot;);<br>return Promise.reject(new Error(&quot;Error&quot;));</pre><h3>Why Use .catch() When .then() Can Handle Errors?</h3><p>The .then() method accepts two callbacks:</p><pre>promise.then(onFulfilled, onRejected);</pre><p>So you might wonder:</p><blockquote><strong><em>Why use </em></strong><strong><em>.catch() if </em></strong><strong><em>.then() already has an error handler?</em></strong></blockquote><p>The answer lies in <strong>what each one catches</strong>.</p><h3>Using .then() for Error Handling</h3><pre>Promise.reject(&quot;Original Error&quot;)<br>    .then(<br>        result =&gt; console.log(result),<br>        err =&gt; console.log(err)<br>    );</pre><p>Output:</p><pre>Original Error</pre><p>The second callback only handles the <strong>original rejection</strong> of the promise.</p><h3>What If the First .then() Throws an Error?</h3><pre>Promise.resolve(&quot;Hello&quot;)<br>    .then(result =&gt; {<br>        throw new Error(&quot;Something broke&quot;);<br>    }, err =&gt; {<br>        console.log(&quot;Rejected&quot;);<br>    });</pre><p>The error is <strong>not caught</strong> by the second callback because it only handles the promise’s initial rejection.</p><p>Instead, the thrown error creates a <strong>new rejected Promise</strong>.</p><h3>Using .catch()</h3><pre>Promise.resolve(&quot;Hello&quot;)<br>    .then(result =&gt; {<br>        throw new Error(&quot;Something broke&quot;);<br>    })<br>    .catch(err =&gt; {<br>        console.log(err.message);<br>    });</pre><p>Output:</p><pre>Something broke</pre><p>.catch() catches:</p><ul><li>The original rejected Promise.</li><li>Any error thrown inside previous .then() callbacks.</li><li>Any Promise rejection returned from previous .then() callbacks.</li></ul><p>You can think of .catch() as a <strong>bottom barrier</strong> for the promise chain.</p><p>Everything above it flows into it if an error occurs.</p><p>Conceptually:</p><pre>Promise<br>↓<br>.then()<br>↓<br>.then()<br>↓<br>.then()<br>↓<br>.catch()</pre><p>If <strong>any</strong> Promise above becomes rejected, or <strong>any</strong> callback throws an error, execution skips directly to .catch().</p><p>This makes .catch() the preferred and most readable way to handle errors in Promise chains.</p><h3>A Common Interview Question</h3><p>Predict the output:</p><pre>async function demo() {<br>console.log(1);<br>    await Promise.resolve();<br>    console.log(2);<br>}<br>console.log(3);<br>demo();<br>console.log(4);</pre><p>Let’s walk through it:</p><ol><li>console.log(3) executes.</li><li>demo() is called.</li><li>Inside demo(), 1 is printed.</li><li>await Promise.resolve() pauses the async function and schedules the remaining code as a microtask.</li><li>console.log(4) executes.</li><li>The current call stack finishes.</li><li>The microtask resumes, printing 2.</li></ol><p>Output:</p><pre>3<br>1<br>4<br>2</pre><p>Understanding this example requires combining knowledge of <strong>async functions</strong>, <strong>Promises</strong>, the <strong>Event Loop</strong>, and the <strong>microtask queue</strong>.</p><h3>Part 13 — Prototypes, Prototype Chain, Constructor Functions, and ES6 Classes</h3><p>One question many beginners ask is:</p><pre>const numbers = [1, 2, 3];<br>numbers.map(...);<br>numbers.filter(...);<br>numbers.reduce(...);<br>numbers.push(...);</pre><p>Where did all these methods come from?</p><p>We never defined them.</p><p>Similarly,</p><pre>const str = &quot;Hello&quot;;<br>str.toUpperCase();<br>str.includes();<br>str.trim();</pre><p>Where do these methods come from?</p><p>The answer is:</p><p><strong>The Prototype Chain.</strong></p><h3>What Is a Prototype?</h3><p>Every JavaScript object has an internal link to another object called its <strong>prototype</strong>.</p><p>If JavaScript cannot find a property on the current object, it automatically looks for that property on the prototype.</p><p>If it’s not found there, JavaScript continues searching higher up the chain.</p><p>This process is called the <strong>Prototype Chain</strong>.</p><h3>Visualizing the Prototype Chain</h3><p>Suppose we have:</p><pre>const user = {<br>    name: &quot;Alice&quot;<br>};</pre><p>Internally, JavaScript stores something conceptually similar to:</p><pre>user<br>↓<br>Prototype<br>↓<br>Object.prototype<br>↓<br>null</pre><p>When we write:</p><pre>user.toString();</pre><p>JavaScript searches like this:</p><pre>user<br>↓<br>Does user have toString?<br>↓<br>No<br>↓<br>Look inside Object.prototype<br>↓<br>Found<br>↓<br>Execute it</pre><p>That’s why every ordinary object automatically has methods like:</p><pre>toString()<br>hasOwnProperty()<br>valueOf()<br>isPrototypeOf()</pre><p>Even though we never defined them ourselves.</p><h3>Demonstrating the Prototype Chain</h3><pre>const user = {<br>    name: &quot;Alice&quot;<br>};<br>console.log(user.hasOwnProperty(&quot;name&quot;));</pre><p>Output:</p><pre>true</pre><p>But where did hasOwnProperty() come from?</p><p>Not from user.</p><p>It comes from Object.prototype.</p><h3>Arrays Also Use Prototypes</h3><p>Consider:</p><pre>const numbers = [1, 2, 3];</pre><p>Can we find:</p><pre>numbers.map</pre><p>Yes.</p><p>Does the array itself contain map?</p><p>No.</p><p>The search works like this:</p><pre>numbers<br>↓<br>Array.prototype<br>↓<br>Object.prototype<br>↓<br>null</pre><p>Since map() exists inside Array.prototype, JavaScript executes it.</p><p>The same applies to:</p><pre>filter()<br>reduce()<br>find()<br>findIndex()<br>forEach()<br>every()<br>some()</pre><p>All of these methods are inherited.</p><h3>Functions Also Have Prototypes</h3><p>Functions are objects too.</p><pre>function greet() {}<br>console.log(typeof greet);</pre><p>Output:</p><pre>function</pre><p>Although typeof reports &quot;function&quot;, functions are still objects and inherit from Function.prototype.</p><p>This is why functions have methods like:</p><pre>call()<br>apply()<br>bind()</pre><p>These methods come from Function.prototype.</p><h3>Constructor Functions</h3><p>Before ES6 introduced classes, constructor functions were the primary way to create multiple objects with shared behavior.</p><p>Example:</p><pre>function User(name, age) {<br>this.name = name;<br>    this.age = age;<br>}</pre><p>Creating objects:</p><pre>const user1 = new User(&quot;Alice&quot;, 24);<br>const user2 = new User(&quot;Bob&quot;, 30);</pre><p>Each object receives its own properties.</p><h3>What Does the new Keyword Do?</h3><p>Many developers memorize new without understanding what it actually does.</p><p>When JavaScript executes:</p><pre>const user = new User(&quot;Alice&quot;, 24);</pre><p>it performs roughly these steps:</p><ol><li>Creates a new empty object.</li><li>Sets the object’s prototype to User.prototype.</li><li>Sets this inside the constructor to the new object.</li><li>Executes the constructor.</li><li>Returns the new object automatically.</li></ol><p>Conceptually:</p><pre>new User()<br>↓<br>{}<br>↓<br>Prototype → User.prototype<br>↓<br>this = {}<br>↓<br>Assign properties<br>↓<br>Return object</pre><h3>Adding Methods Efficiently</h3><p>Suppose we write:</p><pre>function User(name) {<br>this.name = name;<br>    this.sayHello = function () {<br>        console.log(&quot;Hello&quot;);<br>    };<br>}</pre><p>This works.</p><p>However,</p><p>every object gets its own copy of sayHello().</p><pre>User1<br>↓<br>sayHello()<br>User2<br>↓<br>sayHello()<br>User3<br>↓<br>sayHello()</pre><p>That wastes memory.</p><p>Instead, we attach methods to the prototype.</p><pre>function User(name) {<br>this.name = name;<br>}<br>User.prototype.sayHello = function () {<br>    console.log(&quot;Hello&quot;);<br>};</pre><p>Now:</p><pre>User1<br>↓<br>Prototype<br>↓<br>sayHello()<br>User2<br>↓<br>Prototype<br>↓<br>sayHello()<br>User3<br>↓<br>Prototype<br>↓<br>sayHello()</pre><p>All objects share the same method.</p><p>This is much more memory-efficient.</p><h3>Understanding __proto__ vs prototype</h3><p>This is one of the most confusing interview topics.</p><p>Consider:</p><pre>function User() {}</pre><p>There are two different concepts.</p><h3>prototype</h3><p>Exists on functions.</p><pre>User.prototype</pre><p>This object becomes the prototype of every object created using new User().</p><h3>__proto__</h3><p>Exists on objects.</p><pre>const user = new User();<br>console.log(user.__proto__);</pre><p>Conceptually:</p><pre>user.__proto__ === User.prototype</pre><p>Although __proto__ still exists in browsers, modern JavaScript recommends using:</p><pre>Object.getPrototypeOf(user);</pre><p>instead.</p><h3>Checking the Prototype</h3><pre>const user = {};<br>console.log(Object.getPrototypeOf(user));</pre><p>Output:</p><pre>Object.prototype</pre><p>Similarly,</p><pre>const numbers = [];</pre><p>has:</p><pre>Array.prototype</pre><p>as its prototype.</p><h3>The Prototype Chain in Action</h3><p>Suppose:</p><pre>const arr = [1, 2, 3];</pre><p>When JavaScript evaluates:</p><pre>arr.map(...)</pre><p>the search process looks like:</p><pre>arr<br>↓<br>Does arr contain map?<br>↓<br>No<br>↓<br>Array.prototype<br>↓<br>Found<br>↓<br>Execute</pre><p>If JavaScript cannot find the property there:</p><pre>Array.prototype<br>↓<br>Object.prototype<br>↓<br>null</pre><p>If the property isn’t found anywhere in the chain, the result is undefined.</p><h3>ES6 Classes</h3><p>ES6 introduced the class keyword.</p><p>Example:</p><pre>class User {<br>constructor(name) {<br>        this.name = name;<br>    }<br>    greet() {<br>        console.log(&quot;Hello&quot;, this.name);<br>    }<br>}</pre><p>Creating objects:</p><pre>const user = new User(&quot;Alice&quot;);<br>user.greet();</pre><p>Output:</p><pre>Hello Alice</pre><p>This looks similar to Java or C++.</p><p>However,</p><p>it’s actually converted internally into constructor functions and prototypes.</p><p>Classes are syntax — not a different inheritance model.</p><h3>Class Inheritance</h3><p>Suppose:</p><pre>class Animal {<br>speak() {<br>        console.log(&quot;Animal speaks&quot;);<br>    }<br>}</pre><p>Now:</p><pre>class Dog extends Animal {}</pre><p>Creating:</p><pre>const dog = new Dog();<br>dog.speak();</pre><p>Output:</p><pre>Animal speaks</pre><p>Why?</p><p>Because Dog.prototype inherits from Animal.prototype.</p><h3>The super Keyword</h3><p>Sometimes a child class needs to call its parent constructor.</p><pre>class Animal {<br>constructor(name) {<br>        this.name = name;<br>    }<br>}</pre><p>Child:</p><pre>class Dog extends Animal {<br>constructor(name) {<br>        super(name);<br>    }<br>}</pre><p>super() invokes the parent constructor before the child initializes its own properties.</p><p>Inside methods, super.methodName() allows a subclass to invoke the parent&#39;s implementation.</p><h3>Static Methods</h3><p>Normally,</p><p>methods belong to objects.</p><pre>const user = new User(&quot;Alice&quot;);<br>user.greet();</pre><p>Static methods belong to the class itself.</p><pre>class MathHelper {<br>static add(a, b) {<br>        return a + b;<br>    }<br>}</pre><p>Usage:</p><pre>MathHelper.add(10, 20);</pre><p>Output:</p><pre>30</pre><p>Notice:</p><pre>const helper = new MathHelper();<br>helper.add();</pre><p>throws an error because static methods are not available on instances.</p><h3>Private Fields</h3><p>Modern JavaScript introduced private class fields using #.</p><pre>class BankAccount {<br>#balance = 0;<br>    deposit(amount) {<br>        this.#balance += amount;<br>    }<br>    getBalance() {<br>        return this.#balance;<br>    }<br>}</pre><p>Outside the class:</p><pre>account.#balance;</pre><p>produces:</p><pre>SyntaxError</pre><p>The field can only be accessed from within the class itself.</p><p>This provides true encapsulation, something that earlier JavaScript versions achieved using closures.</p><h3>Instance Methods vs Static Methods</h3><pre>class User {<br>greet() {<br>        console.log(&quot;Hello&quot;);<br>    }<br>    static createGuest() {<br>        return new User();<br>    }<br>}</pre><p>Usage:</p><pre>const user = new User();<br>user.greet();</pre><p>Valid.</p><pre>User.createGuest();</pre><p>Also valid.</p><p>But:</p><pre>user.createGuest();</pre><p>is invalid because createGuest() is a static method.</p><h3>A Common Interview Question</h3><p>Predict the output:</p><pre>class Person {<br>sayHello() {<br>        console.log(&quot;Hello&quot;);<br>    }<br>}<br>const p = new Person();<br>console.log(p.hasOwnProperty(&quot;sayHello&quot;));</pre><p>Output:</p><pre>false</pre><p>Why?</p><p>Because sayHello() is stored on Person.prototype, not directly on the object instance.</p><p>However:</p><pre>console.log(&quot;sayHello&quot; in p);</pre><p>Output:</p><pre>true</pre><p>The in operator checks both the object&#39;s own properties and everything available through its prototype chain.</p><h3>Part 14 — Modules, Strict Mode, Symbols, Iterators, Generators, WeakMap, and Memory Management</h3><p>As JavaScript applications grew larger, developers faced a common problem.</p><p>Imagine writing an application with thousands of lines of code in a single file.</p><pre>app.js<br>10000+ lines</pre><p>Everything lived in one place.</p><p>Variables accidentally overwrote one another.</p><p>Functions with the same name caused conflicts.</p><p>Maintaining the project became increasingly difficult.</p><p>JavaScript introduced <strong>modules</strong> to solve this problem.</p><h3>What Is a Module?</h3><p>A module is simply a JavaScript file with its own scope.</p><p>Variables declared inside one module are not automatically visible in another module.</p><p>For example:</p><pre>// math.js<br>const PI = 3.14159;<br>function add(a, b) {<br>    return a + b;<br>}</pre><p>Another file cannot access these directly unless they are explicitly exported.</p><p>Modules encourage encapsulation and make large applications easier to organize.</p><h3>Exporting Values</h3><p>There are two primary ways to export values from a module.</p><h3>Named Exports</h3><pre>// math.js<br>export const PI = 3.14159;<br>export function add(a, b) {<br>    return a + b;<br>}</pre><p>Importing them:</p><pre>import { PI, add } from &quot;./math.js&quot;;<br>console.log(add(10, 20));</pre><p>Output:</p><pre>30</pre><p>Named exports are useful when a module exposes multiple functions or constants.</p><h3>Default Exports</h3><p>Sometimes a module has one primary export.</p><pre>// logger.js<br>export default function log(message) {<br>    console.log(message);<br>}</pre><p>Import:</p><pre>import log from &quot;./logger.js&quot;;<br>log(&quot;Hello&quot;);</pre><p>Unlike named exports, default exports can be imported using any variable name.</p><pre>import print from &quot;./logger.js&quot;;</pre><p>This works because there can only be one default export per module.</p><h3>Named vs Default Exports</h3><p>A common interview question is:</p><p>Can a module have both named and default exports?</p><p>Yes.</p><p>Example:</p><pre>export const version = &quot;1.0&quot;;<br>export default function greet() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><p>Import:</p><pre>import greet, { version } from &quot;./module.js&quot;;</pre><h3>Importing Everything</h3><p>Sometimes you want every named export.</p><pre>import * as MathUtils from &quot;./math.js&quot;;<br>console.log(MathUtils.PI);<br>console.log(MathUtils.add(10, 20));</pre><p>This collects all named exports into a single object.</p><h3>CommonJS vs ES Modules</h3><p>Before ES Modules became standard, Node.js primarily used <strong>CommonJS</strong>.</p><p>CommonJS:</p><pre>const math = require(&quot;./math&quot;);<br>math.add(10, 20);</pre><p>Export:</p><pre>module.exports = {<br>add,<br>    subtract<br>};</pre><p>Modern JavaScript uses <strong>ES Modules</strong>.</p><pre>import { add } from &quot;./math.js&quot;;</pre><p>Export:</p><pre>export function add() {}</pre><p>Today, browsers natively support ES Modules, and modern versions of Node.js support them as well.</p><p>While you’ll still encounter CommonJS in older codebases, ES Modules are the preferred standard for new projects.</p><h3>Strict Mode</h3><p>JavaScript was originally designed with several behaviors that made it easy to write code but also easy to introduce subtle bugs.</p><p>Strict Mode enables a stricter parsing and error-handling mode that catches many common mistakes.</p><p>Enable it with:</p><pre>&quot;use strict&quot;;</pre><p>at the top of a script or function.</p><h3>Accidental Global Variables</h3><p>Without strict mode:</p><pre>name = &quot;Alice&quot;;<br>console.log(name);</pre><p>Output:</p><pre>Alice</pre><p>JavaScript silently creates a global variable.</p><p>With strict mode:</p><pre>&quot;use strict&quot;;<br>name = &quot;Alice&quot;;</pre><p>Output:</p><pre>ReferenceError</pre><p>Strict mode helps prevent accidental globals.</p><h3>Duplicate Parameters</h3><p>Without strict mode:</p><pre>function add(a, a) {<br>return a;<br>}</pre><p>This is allowed in non-strict mode.</p><p>With strict mode:</p><pre>SyntaxError</pre><p>Duplicate parameter names are not permitted.</p><h3>Why ES Modules Are Strict by Default</h3><p>An important point is that <strong>every ES Module automatically runs in strict mode</strong>.</p><p>That means you do <strong>not</strong> need to write:</p><pre>&quot;use strict&quot;;</pre><p>inside modules.</p><p>This is one of the reasons modern JavaScript projects rarely include the directive explicitly.</p><h3>Symbols</h3><p>Suppose two different libraries both use the same property name.</p><pre>const user = {<br>id: 1<br>};</pre><p>Another library also adds:</p><pre>user.id = 999;</pre><p>The original value is overwritten.</p><p>Symbols solve this problem by creating unique property keys.</p><h3>Creating a Symbol</h3><pre>const id = Symbol();<br>const user = {<br>    [id]: 1<br>};</pre><p>Notice the square brackets.</p><p>Symbols must be used as computed property names.</p><h3>Every Symbol Is Unique</h3><pre>const a = Symbol();<br>const b = Symbol();<br>console.log(a === b);</pre><p>Output:</p><pre>false</pre><p>Even if they appear identical, each Symbol is unique.</p><h3>Why Use Symbols?</h3><p>Symbols are useful when:</p><ul><li>Creating unique property keys.</li><li>Avoiding naming collisions between libraries.</li><li>Defining well-known behaviors (such as custom iterators).</li></ul><p>Although they are less common in everyday application code, many built-in JavaScript features use Symbols internally.</p><h3>Iterables</h3><p>You’ve already used iterable objects many times.</p><pre>const numbers = [1, 2, 3];</pre><p>Why does this work?</p><pre>for (const value of numbers) {<br>console.log(value);<br>}</pre><p>Because arrays are <strong>iterable</strong>.</p><p>Strings are iterable.</p><p>Maps are iterable.</p><p>Sets are iterable.</p><p>Objects, however, are <strong>not</strong> iterable by default.</p><pre>const user = {<br>name: &quot;Alice&quot;<br>};<br>for (const item of user) {<br>}</pre><p>Output:</p><pre>TypeError</pre><h3>Iterators</h3><p>Behind every iterable object is an <strong>iterator</strong>.</p><p>Conceptually, an iterator answers two questions:</p><ol><li>What’s the next value?</li><li>Are we finished?</li></ol><p>The iterator protocol is implemented through the next() method.</p><p>Example:</p><pre>const arr = [10, 20, 30];<br>const iterator = arr[Symbol.iterator]();<br>console.log(iterator.next());</pre><p>Output:</p><pre>{ value: 10, done: false }</pre><p>Calling it again:</p><pre>console.log(iterator.next());</pre><p>Output:</p><pre>{ value: 20, done: false }</pre><p>Eventually:</p><pre>{ value: undefined, done: true }</pre><p>This is exactly what for...of does behind the scenes.</p><h3>Generators</h3><p>Writing custom iterators manually can be tedious.</p><p>Generators simplify the process.</p><p>A generator is a special function declared with function*.</p><pre>function* numbers() {<br>yield 1;<br>    yield 2;<br>    yield 3;<br>}</pre><p>Calling it:</p><pre>const generator = numbers();</pre><p>Nothing executes immediately.</p><p>Each call to:</p><pre>generator.next();</pre><p>continues execution until the next yield.</p><p>Example:</p><pre>console.log(generator.next());</pre><p>Output:</p><pre>{ value: 1, done: false }</pre><p>Second call:</p><pre>console.log(generator.next());</pre><p>Output:</p><pre>{ value: 2, done: false }</pre><p>Third call:</p><pre>console.log(generator.next());</pre><p>Output:</p><pre>{ value: 3, done: false }</pre><p>Finally:</p><pre>console.log(generator.next());</pre><p>Output:</p><pre>{ value: undefined, done: true }</pre><p>Generators are commonly used for lazy evaluation, custom iteration, and controlling asynchronous flows in some libraries.</p><h3>Memory Management</h3><p>JavaScript automatically manages memory.</p><p>When you create an object:</p><pre>const user = {<br>name: &quot;Alice&quot;<br>};</pre><p>JavaScript allocates memory for it.</p><p>When the object is no longer reachable, the JavaScript engine automatically reclaims that memory through <strong>Garbage Collection</strong>.</p><p>Unlike languages such as C or C++, developers do not manually allocate or free memory.</p><h3>Garbage Collection</h3><p>Garbage collection is the process of identifying objects that are no longer reachable and freeing the memory they occupy.</p><p>Conceptually:</p><pre>Create Object<br>↓<br>Use Object<br>↓<br>No References Left<br>↓<br>Garbage Collector Removes It</pre><p>This helps prevent many memory-management bugs, though it’s still possible to create memory leaks by unintentionally keeping references alive.</p><h3>WeakMap</h3><p>A WeakMap is similar to a Map, but its keys must be objects.</p><pre>const weakMap = new WeakMap();<br>const user = {<br>    name: &quot;Alice&quot;<br>};<br>weakMap.set(user, &quot;Premium&quot;);</pre><p>If user is no longer referenced anywhere else, both the object and its associated entry in the WeakMap become eligible for garbage collection.</p><p>This behavior makes WeakMap useful for storing metadata tied to objects without preventing those objects from being cleaned up.</p><p>Unlike Map, a WeakMap cannot be iterated over because its contents can disappear at any time.</p><h3>WeakSet</h3><p>WeakSet behaves similarly.</p><pre>const weakSet = new WeakSet();<br>const user = {<br>    name: &quot;Alice&quot;<br>};<br>weakSet.add(user);</pre><p>If the object is no longer reachable elsewhere in the program, it may be garbage collected, and the corresponding entry in the WeakSet disappears automatically.</p><p>Like WeakMap, WeakSet is not iterable.</p><p>Map vs WeakMap</p><pre>| Feature                     | Map       | WeakMap      |<br>| --------------------------- | --------- | ------------ |<br>| Key Types                   | Any value | Objects only |<br>| Iterable                    | ✅ Yes     | ❌ No         |<br>| Prevents Garbage Collection | ✅ Yes     | ❌ No         |<br>| Size Property               | ✅ Yes     | ❌ No         |</pre><p>Set vs WeakSet</p><pre>| Feature                     | Set       | WeakSet      |<br>| --------------------------- | --------- | ------------ |<br>| Values                      | Any value | Objects only |<br>| Iterable                    | Yes       | No           |<br>| Size Property               | Yes       | No           |<br>| Prevents Garbage Collection | Yes       | No           |</pre><h3>A Common Interview Question</h3><p>What is the difference between Map and a plain JavaScript object?</p><p>A plain object is primarily designed to store key-value pairs where keys are strings or Symbols. A Map is designed specifically as a key-value collection and allows keys of <strong>any type</strong>, including objects and functions.</p><p>Example:</p><pre>const map = new Map();<br>const key = {};<br>map.set(key, &quot;value&quot;);<br>console.log(map.get(key));</pre><p>Output:</p><pre>value</pre><p>With a plain object, using an object as a key is not supported in the same way because object property keys are coerced to strings (unless they are Symbols).</p><h3>Part 15 — Advanced JavaScript Concepts and Interview Topics</h3><p>By now you’ve learned the syntax, asynchronous programming, prototypes, and modules.</p><p>This final chapter covers the remaining advanced concepts every JavaScript developer should know:</p><ul><li>Execution Context</li><li>this</li><li>call(), apply(), and bind()</li><li>Currying</li><li>Memoization</li><li>Debouncing</li><li>Throttling</li><li>Event Delegation</li><li>Property Descriptors</li><li>Proxy and Reflect</li><li>Floating-Point Precision</li><li>Common JavaScript Pitfalls</li></ul><h3>Execution Context</h3><p>Whenever JavaScript executes code, it creates an <strong>Execution Context</strong>.</p><p>Think of it as the environment in which your code runs.</p><p>Every execution context contains:</p><ul><li>Variable Environment</li><li>Lexical Environment</li><li>this Binding</li></ul><p>There are three main types of execution contexts:</p><ol><li>Global Execution Context</li><li>Function Execution Context</li><li>Eval Execution Context (rarely used)</li></ol><h3>Global Execution Context</h3><p>When JavaScript starts running,</p><p>it first creates the Global Execution Context.</p><pre>console.log(&quot;Hello&quot;);</pre><p>Internally:</p><pre>Global Execution Context<br>↓<br>Variables<br>↓<br>Functions<br>↓<br>this<br>↓<br>Execute Code</pre><p>Only one Global Execution Context exists for a program.</p><h3>Function Execution Context</h3><p>Each function call creates a new execution context.</p><pre>function greet() {<br>console.log(&quot;Hello&quot;);<br>}<br>greet();</pre><p>Execution:</p><pre>Global Context<br>↓<br>Function Context<br>↓<br>Execute<br>↓<br>Destroy Context</pre><p>Every function call creates a fresh execution context.</p><h3>Understanding this</h3><p>One of the most confusing topics in JavaScript is the this keyword.</p><p>Many beginners think:</p><blockquote><em>“this always refers to the object.&quot;</em></blockquote><p>Not exactly.</p><p>The value of this depends on <strong>how a function is called</strong>, not where it is written (with the exception of arrow functions, which inherit this lexically).</p><h3>Default Binding</h3><pre>function show() {<br>console.log(this);<br>}<br>show();</pre><p>In non-strict mode inside a browser,</p><p>this refers to:</p><pre>window</pre><p>In strict mode:</p><pre>&quot;use strict&quot;;<br>function show() {<br>    console.log(this);<br>}<br>show();</pre><p>Output:</p><pre>undefined</pre><h3>Implicit Binding</h3><pre>const user = {<br>name: &quot;Alice&quot;,<br>    greet() {<br>        console.log(this.name);<br>    }<br>};<br>user.greet();</pre><p>Output:</p><pre>Alice</pre><p>Here,</p><p>this refers to user.</p><h3>Explicit Binding</h3><p>JavaScript lets us explicitly choose the value of this.</p><h3>call()</h3><pre>function greet(city) {<br>console.log(this.name, city);<br>}<br>const user = {<br>    name: &quot;Alice&quot;<br>};<br>greet.call(user, &quot;London&quot;);</pre><p>Output:</p><pre>Alice London</pre><p>call() invokes the function immediately.</p><p>Arguments are passed individually.</p><h3>apply()</h3><pre>greet.apply(user, [&quot;London&quot;]);</pre><p>Output:</p><pre>Alice London</pre><p>The only difference is that arguments are passed as an array.</p><h3>bind()</h3><p>Unlike call() and apply(),</p><p>bind() does <strong>not</strong> execute the function.</p><p>Instead,</p><p>it returns a new function.</p><pre>const greetLondon = greet.bind(user, &quot;London&quot;);<br>greetLondon();</pre><p>Output:</p><pre>Alice London</pre><p>This is particularly useful when passing methods as callbacks while preserving the desired this value.</p><h3>Currying</h3><p>Currying transforms a function that takes multiple arguments into a sequence of functions that each take a single argument.</p><p>Instead of:</p><pre>add(10, 20);</pre><p>we write:</p><pre>add(10)(20);</pre><p>Implementation:</p><pre>function add(a) {<br>return function (b) {<br>        return a + b;<br>    };<br>}<br>console.log(add(10)(20));</pre><p>Output:</p><pre>30</pre><p>Currying is useful for creating reusable, partially applied functions.</p><h3>Memoization</h3><p>Suppose a function performs an expensive calculation.</p><pre>function square(n) {<br>return n * n;<br>}</pre><p>If we repeatedly call:</p><pre>square(1000);</pre><p>the result is recalculated every time.</p><p>Memoization stores previous results.</p><pre>function memoizedSquare() {<br>const cache = {};<br>    return function (n) {<br>        if (cache[n]) {<br>            return cache[n];<br>        }<br>        cache[n] = n * n;<br>        return cache[n];<br>    };<br>}</pre><p>Now repeated calls return cached values instead of recalculating them.</p><p>Memoization is especially valuable in recursive algorithms, dynamic programming, and performance-sensitive applications.</p><h3>Debouncing</h3><p>Imagine a search bar.</p><p>Every keystroke triggers:</p><pre>H<br>He<br>Hel<br>Hell<br>Hello</pre><p>Without debouncing,</p><p>five API requests would be sent.</p><p>Debouncing waits until the user stops typing.</p><pre>Typing<br>↓<br>Typing<br>↓<br>Typing<br>↓<br>Pause<br>↓<br>Send One Request</pre><p>A common implementation:</p><pre>function debounce(fn, delay) {<br>let timer;<br>    return function (...args) {<br>        clearTimeout(timer);<br>        timer = setTimeout(() =&gt; {<br>            fn(...args);<br>        }, delay);<br>    };<br>}</pre><p>Typical use cases:</p><ul><li>Search boxes</li><li>Auto-save</li><li>Window resizing</li></ul><h3>Throttling</h3><p>Throttling is different.</p><p>Instead of waiting,</p><p>it limits how often a function can execute.</p><p>Example:</p><pre>Scroll Event<br>1000 times<br>↓<br>Throttle<br>↓<br>Run Every 100ms</pre><p>Throttling is commonly used for:</p><ul><li>Scrolling</li><li>Mouse movement</li><li>Window resize events</li><li>Infinite scrolling</li></ul><h3>Event Delegation</h3><p>Suppose a page contains 1,000 buttons.</p><p>Without event delegation:</p><pre>button1.addEventListener(...);<br>button2.addEventListener(...);<br>button3.addEventListener(...);</pre><p>This creates many event listeners.</p><p>Instead, attach one listener to a common parent.</p><pre>list.addEventListener(&quot;click&quot;, event =&gt; {<br>if (event.target.matches(&quot;button&quot;)) {<br>        console.log(&quot;Button clicked&quot;);<br>    }<br>});</pre><p>Benefits:</p><ul><li>Better performance</li><li>Less memory usage</li><li>Automatically handles dynamically added elements</li></ul><h3>Property Descriptors</h3><p>Every object property has metadata.</p><p>Example:</p><pre>const user = {<br>name: &quot;Alice&quot;<br>};<br>console.log(<br>    Object.getOwnPropertyDescriptor(user, &quot;name&quot;)<br>);</pre><p>Output:</p><pre>{<br>    value: &quot;Alice&quot;,<br>writable: true,<br>    enumerable: true,<br>    configurable: true<br>}</pre><p>These attributes determine how a property behaves.</p><h3>Object.freeze()</h3><p>Frozen objects cannot be modified.</p><pre>const user = {<br>name: &quot;Alice&quot;<br>};<br>Object.freeze(user);<br>user.name = &quot;Bob&quot;;</pre><p>Output:</p><pre>No change</pre><p>No properties can be added, removed, or modified.</p><h3>Object.seal()</h3><pre>Object.seal(user);</pre><p>You may modify existing properties.</p><p>You cannot add or remove properties.</p><h3>Object.preventExtensions()</h3><pre>Object.preventExtensions(user);</pre><p>New properties cannot be added.</p><p>Existing ones may still be modified or deleted (if configurable).</p><h3>Proxy</h3><p>A Proxy intercepts operations performed on an object.</p><p>Example:</p><pre>const user = {<br>name: &quot;Alice&quot;<br>};<br>const proxy = new Proxy(user, {<br>    get(target, property) {<br>        console.log(&quot;Reading&quot;, property);<br>        return target[property];<br>    }<br>});<br>console.log(proxy.name);</pre><p>Output:</p><pre>Reading name<br>Alice</pre><p>Proxies are useful for validation, logging, access control, and building reactive systems.</p><p>Frameworks such as Vue 3 use Proxies extensively to implement reactivity.</p><h3>Reflect</h3><p>Reflect provides methods that correspond to many object operations.</p><p>Instead of:</p><pre>target[property]</pre><p>inside a Proxy,</p><p>you can write:</p><pre>Reflect.get(target, property);</pre><p>Using Reflect makes Proxy handlers more predictable and mirrors the default behavior of JavaScript.</p><h3>Floating-Point Precision</h3><p>One of JavaScript’s classic surprises:</p><pre>console.log(0.1 + 0.2);</pre><p>Output:</p><pre>0.30000000000000004</pre><p>Why?</p><p>JavaScript stores numbers using the IEEE 754 floating-point format.</p><p>Many decimal fractions cannot be represented exactly in binary.</p><p>A common way to compare floating-point values is:</p><pre>const result = Math.abs((0.1 + 0.2) - 0.3) &lt; Number.EPSILON;<br>console.log(result);</pre><p>Output:</p><pre>true</pre><h3>Common JavaScript Pitfalls</h3><h3>Assignment vs Comparison</h3><pre>if (x = 5) {}</pre><p>This assigns 5 to x.</p><p>Use:</p><pre>if (x === 5) {}</pre><h3>== vs ===</h3><p>Prefer:</p><pre>===</pre><p>because it avoids implicit type coercion.</p><pre>0 == false</pre><p>Output:</p><pre>true</pre><p>Whereas:</p><pre>0 === false</pre><p>Output:</p><pre>false</pre><h3>The arguments Object</h3><p>Every <strong>regular function</strong> in JavaScript has access to a special object called arguments.</p><p>It contains <strong>all the arguments passed to the function</strong>, regardless of how many parameters are defined.</p><p>Unlike an array, arguments is an <strong>array-like object</strong>.</p><p>This means:</p><ul><li>It stores values using numeric indexes.</li><li>It has a length property.</li><li>It is <strong>not</strong> an actual Array.</li></ul><p>Example:</p><pre>function showArgs(a, b) {console.log(arguments[0]);<br>    console.log(arguments[1]);<br>}<br>showArgs(&quot;Hello&quot;, &quot;World&quot;);</pre><p>Output:</p><pre>Hello<br>World</pre><p>Here, the values passed to the function can be accessed using indexes, just like an array.</p><h3>Why Is It Called an Array-Like Object?</h3><p>The arguments object looks similar to an array because it has indexed elements and a length property.</p><pre>function demo() {console.log(arguments);<br>}</pre><p>Calling:</p><pre>demo(10, 20, 30);</pre><p>Conceptually produces:</p><pre>{<br>    0: 10,<br>    1: 20,<br>    2: 30,<br>    length: 3<br>}</pre><p>However, it is <strong>not</strong> an actual Array.</p><h3>Limitations</h3><p>Since arguments is not an Array, it doesn&#39;t have array methods like:</p><ul><li>map()</li><li>filter()</li><li>forEach()</li><li>reduce()</li></ul><p>Example:</p><pre>function demo() {<br>arguments.forEach(() =&gt; {});<br>}</pre><p>Output:</p><pre>TypeError: arguments.forEach is not a function</pre><p>You can still iterate over it using loops because it supports indexes and has a length property.</p><p>Example</p><pre>function sumAll() {<br>let total = 0;<br>    for (let i = 0; i &lt; arguments.length; i++) {<br>        total += arguments[i];<br>    }<br>    return total;<br>}<br>console.log(sumAll(10, 20, 30, 40));</pre><p>Output:</p><pre>100</pre><p>The function doesn’t need to know beforehand how many arguments will be passed.</p><h3>arguments Is Not Available in Arrow Functions</h3><p>One important limitation is that the arguments object exists <strong>only in regular functions</strong>.</p><p>Arrow functions do <strong>not</strong> have their own arguments object.</p><pre>const demo = () =&gt; {<br>console.log(arguments);<br>};</pre><p>Output:</p><pre>ReferenceError: arguments is not defined</pre><p>This is because arrow functions do not create their own execution context and therefore don’t receive their own arguments object.</p><h3>Rest Parameters (...args)</h3><p>In modern JavaScript, <strong>Rest Parameters</strong> are preferred over the arguments object.</p><pre>function sumAll(...args) {<br>console.log(args);<br>}<br>sumAll(10, 20, 30);</pre><p>Output:</p><pre>[<br>    10,<br>    20,<br>    30<br>]</pre><p>Unlike arguments, args is a <strong>real Array</strong>, so you can directly use array methods.</p><p>Example:</p><pre>function double(...args) {<br>return args.map(num =&gt; num * 2);<br>}<br>console.log(double(1, 2, 3));</pre><p>Output:</p><pre>[<br>    2,<br>    4,<br>    6<br>]</pre><p>Rest parameters also work in arrow functions.</p><pre>const sum = (...args) =&gt; {<br>return args.reduce((a, b) =&gt; a + b, 0);<br>};<br>console.log(sum(1, 2, 3));</pre><p>Output:</p><pre>6</pre><h3>Why Prefer Rest Parameters?</h3><p>Compared to the arguments object, Rest Parameters offer several advantages:</p><ul><li>They are <strong>real arrays</strong>.</li><li>They support all array methods (map(), filter(), reduce(), etc.).</li><li>They work in both regular and arrow functions.</li><li>They provide cleaner and more readable syntax.</li></ul><p>For these reasons, modern JavaScript code almost always uses <strong>Rest Parameters (</strong><strong>...args)</strong> instead of the arguments object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68439d1a95fe" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-complete-javascript-handbook-from-basics-to-advanced-concepts-68439d1a95fe">The Complete JavaScript Handbook: From Basics to Advanced Concepts</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Park+ Interview Experience (Frontend Intern, 2025)]]></title>
            <link>https://medium.com/@farhinbashira/my-park-interview-experience-frontend-intern-2025-39580396fff6?source=rss-8d2e3a58af0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/39580396fff6</guid>
            <dc:creator><![CDATA[Bashira Farhin]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 14:22:09 GMT</pubDate>
            <atom:updated>2026-08-08T17:24:10.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*9RVmVqtEsPIEONKEbl3LXQ.png" /></figure><p>In early 2025, I got an opportunity to interview for a <strong>Frontend Intern role at Park+</strong>. The recruiter actually found my profile on <strong>Naukri</strong> while searching with certain keywords, and that’s how he reached out to me.</p><h3>Phone-Screening Round</h3><p>You can call this the <strong>initial screening round</strong>, or not even a proper round at all. It was more of a casual conversation where the recruiter wanted to know about me and also guide me about the process.</p><p>Here’s what he asked me:</p><ul><li><strong>Introduction about myself</strong></li><li><strong>Details of my internship</strong></li><li><strong>CSS3 Preprocessors</strong></li><li><strong>Redux</strong> <strong>basics</strong></li><li><strong>Props drilling</strong></li><li><strong>What is Virtual DOM?</strong></li><li><strong>How to manage deep state</strong></li><li><strong>useContext hook</strong></li></ul><p>After that, he also told me what kind of topics and questions I should expect in <strong>Round 1</strong>, which helped me prepare better.</p><h3>Round 1 — Technical with SD-II (Frontend)</h3><p>This round started with a quick introduction. Then, the interviewer went deeper into my experience:</p><ul><li>He picked <strong>specific words from my resume/project</strong>. For example, when I mentioned “AuthWrapper,” he asked:</li><li>What is AuthWrapper?</li><li>What is a Slice in Redux?</li><li>How did you create a userSlice?</li><li>Then came <strong>JavaScript basics(</strong><em>all were asked through questions in Google Docs</em><strong>)</strong>:</li><li>Scope</li><li>Closures</li><li>Promises (e.g., “Print your name after 5 seconds using Promises”)</li><li>Classic setTimeout questions:</li></ul><p><em>(function() { <br> console.log(1); <br> setTimeout(function(){console.log(2)}, 1000); <br> setTimeout(function(){console.log(3)}, 0); <br> console.log(4); <br>})();</em></p><p>React task:</p><ul><li>Opened <strong>CodeSandbox</strong> and created a small project.</li><li>Fetch API to display a user list.</li><li>Added a <strong>search box</strong> so that as the user typed, it filtered the names dynamically.</li></ul><p>The interviewer was quite encouraging and said he was <strong>impressed</strong>, so I moved to Round 2.</p><h3>Round 2 — Technical with SD-III (Frontend)</h3><p>This round was <strong>project and javascript focused</strong>.</p><ul><li>Again, started with a short intro.</li><li>He picked lines from my resume and projects like “optimized performance by 30%” and asked, <em>“How did you achieve this optimization?”</em></li><li>Sessions</li><li>Browser Storage</li><li>LocalStorage vs SessionStorage</li><li>closures</li><li>debouncing (<em>he told me to write the code for this</em>)</li></ul><h3>Coding Question</h3><p>I was given a <strong>JavaScript problem</strong> to merge user sessions:</p><p><em>const sessions = [ <br> { user: 8, duration: 50, equipment: [‘bench’] }, <br> { user: 7, duration: 150, equipment: [‘dumbbell’] }, <br> { user: 1, duration: 10, equipment: [‘barbell’] }, <br> { user: 7, duration: 100, equipment: [‘bike’, ‘kettlebell’] }, <br> { user: 7, duration: 200, equipment: [‘bike’] }, <br> { user: 2, duration: 200, equipment: [‘treadmill’] }, <br> { user: 2, duration: 200, equipment: [‘bike’] }, <br>];<br></em>The task:</p><ul><li>Merge sessions by user.</li><li><strong>Sum up durations.</strong></li><li><strong>Combine equipment</strong>, remove duplicates, and sort alphabetically.</li></ul><p>I solved it with some hints, and the interviewer was happy.</p><h3>Round 3 — With the CTO</h3><p>This was the <strong>weirdest round</strong> for me.</p><p>He asked <strong>React questions</strong>, like:</p><ul><li>What is React?</li><li>Why React over plain JavaScript?</li><li>Follow-ups like <em>“What more?”</em> multiple times — which made me a little nervous.</li><li>Asked about <strong>PWA (Progressive Web Apps)</strong> and <strong>Service Workers</strong> (which I wasn’t very familiar with).</li></ul><h3>System Design Task</h3><p>Finally, he gave me a <strong>React design problem</strong>:</p><ul><li>Design an <strong>Instagram-like feed system</strong>.</li><li>One page for the main feed (posts from friends).</li><li>Another page for general/public posts.</li><li>A user profile page when clicking on a username.</li><li>Handle <strong>state management</strong> properly across these pages.</li></ul><p>I opened my editor and started by writing <strong>basic components</strong> (like Post, Home, and Feed). I even set up some structure for state handling. But I got <strong>stuck halfway through</strong> — I wasn’t sure how to proceed with the shared state and Redux slices the way he expected.</p><p>At one point, I misunderstood and started writing components (Post, Home, Feed), but he clarified that he wanted to see how I’d manage <strong>shared state with Redux slices</strong>.</p><p>Finally, he asked me to <strong>self-rate</strong>:</p><ul><li>HTML</li><li>CSS</li></ul><h3>Final Outcome</h3><p>After completing all three rounds, I got a call from HR, followed by a rejection email the very next day — which was quite obvious because of the <em>mistakes</em> I made in Round 3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39580396fff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>