<?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"><channel><title><![CDATA[Aftab Alam's Blog]]></title><description><![CDATA[Aftab Alam's Blog]]></description><link>https://aalam.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 09 Nov 2026 04:46:23 GMT</lastBuildDate><atom:link href="https://aalam.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Standalone Angular Components - A world without ngModule]]></title><description><![CDATA[Know about Angular standalone components and how it simplifies your Angular code]]></description><link>https://aalam.hashnode.dev/standalone-angular-components-a-world-without-ngmodule</link><guid isPermaLink="true">https://aalam.hashnode.dev/standalone-angular-components-a-world-without-ngmodule</guid><category><![CDATA[Angular]]></category><category><![CDATA[frontend]]></category><category><![CDATA[tooling]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Aftab Alam]]></dc:creator><pubDate>Sat, 14 May 2022 17:03:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1652547798280/moDSKRqFr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Angular has come a long way since its inception, widespread use in its first incarnation(a.k.a Angular JS), and today being embraced as the de-facto one-stop framework to build a modern enterprise-ready, browser-based applications/SPAs. One thing that I personally appreciate, more than anything between its different major releases is its focus on developer productivity, ability to innovate(and re-invent) without comprising on the aspects that let us build robust, modular, and highly scalable applications. But, achieving a fine balance between developer experience and knowing enough about your code to infer, and guarantee robustness is easier said than done. A one-stop tool doesn’t need to worry just about the essentials to get you going but also needs to be meticulously focused on giving you the right foundations for you to orchestrate an entire system that scales both for new code as well as pre-existing, large codebases. <code>NgModule</code> is one such construct that informs Angular of the different logical(and by effect, physical) boundaries of your code. It lays out the foundation to separate concerns by features, declare dependencies, encapsulate logic, expose what’s accessible outside its realm, etc. that can be stitched together to make an entire Angular application. As an auxiliary need, introduce concepts like lazy loading, and bootstrap application through one true <code>AppModule</code>. What components do for the presentation layer is what <code>ngModule</code> does for Angular.</p>
<p>But, <code>ngModule</code> has garnered quite a love/hate relationship with developers over time...okay, largely love ❤️, but there are aspects that leave things to be desired. In this article we’ll know how Angular’s enhancing the <code>ngModule</code> experience through Angular Standalone components, a key paradigm shift in how we structure Angular code. But before diving into that, let’s understand how we got here.</p>
<h3 id="heading-developer-challenges-with-ngmodule">Developer Challenges with <code>ngModule</code></h3>
<p><code>ngModule</code> introduces an additional learning curve, requires extra configurations, and takes a bit of work before you get a component’s structure. By their definition and use, components, directives, and pipes can be assumed standalone within the module boundaries. To carry beyond boundaries, you’ll have to carry all of the module - a bag full of goodies. It has served us quite well but it leads to a bit of <em>limiting</em> development experience, and missing a bit of discipline and forethought makes taking decisions and navigating freely harder as your app grows. You get some readability benefits at the <code>ngModule</code> level but lose some of the portability, discover friction, bugs and bottlenecks in scaling the app, or improving its performance. The additional ceremony(and overhead), although necessary seemingly leads to a learning curve and sometimes, <a target="_blank" href="https://stackoverflow.com/questions/39713306/understanding-ngmodule-usage">relatively more complex</a>,  less appealing or easy enough for beginners. </p>
<blockquote>
<p>The trouble with <code>ngModule</code> increases with the size and complexity if you’re not upfront aware and thoughtful of how your App's gonna evolve. It requires good developer care and good gate-keeping to keep complexity and app size bloat at bay.</p>
</blockquote>
<p>To deal with some of the mentioned shortcomings people came up with concepts like SCAM(Single Component Application Module)</p>
<h3 id="heading-scam-single-component-application-module">SCAM - Single Component Application Module</h3>
<p>SCAM is a community-envisioned approach to co-locate components and <code>ngModule</code> to reduce the amount of work needed to organise and understand a component in its entirety. you place <code>ngModule</code> in the same file as your component and focus on single-responsibility and more modular components and modules to increase port-ability of common behavioural/presentational code beyond the logical fences. This approach re-invents the app writing style in the user-land, and aids in providing flexibility with organising code, lazy loading more atomic chunks, etc. but doesn't change anything much about how Angular works and still expects everything. You can know more about the SCAM approach <a target="_blank" href="https://medium.com/marmicode/your-angular-module-is-a-scam-b4136ca3917b">here</a> and <a target="_blank" href="https://sandroroth.com/blog/angular-shared-scam">here</a>.</p>
<h2 id="heading-standalone-componentspipesdirectives">Standalone Components/Pipes/Directives</h2>
<p>Standalone components are Angular's take on simplifying Angular code and are an answer to the aforementioned concerns. Angular is known for course correcting and continuously innovating the developer ergonomics. With Angular 14, as developers, you’d get an opportunity to say <em>tada</em> <strong>👋</strong> to <code>ngModule</code> for most of your components, directives, pipes, etc. Your components, directives, and pipes can be more of a single-file components/directives/pipes(or, single source of truth), with everything essential to them co-located.</p>
<p>With Angular’s standalone component’s role known, let’s see how we can use it today!</p>
<h3 id="heading-working-with-standalone-components-today">Working with Standalone Components today</h3>
<p>To start a new <code>ng-14</code> project today, run the following command in your terminal</p>
<pre><code class="lang-shell">npx @angular/cli@next new ng14
</code></pre>
<p>This will scaffold a new Angular project for you(with 14.0.0-rc.0), with the conventional structure - One <code>AppComponent</code> </p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./app.component.css'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent {
  title = <span class="hljs-string">'ng14'</span>;
}
</code></pre>
<p>included in one <code>AppModule</code> </p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;

<span class="hljs-keyword">import</span> { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;

<span class="hljs-meta">@NgModule</span>({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule { }
</code></pre>
<p>initialised by your <code>main.ts</code></p>
<pre><code class="lang-ts">
<span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app/app.module'</span>;

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));
</code></pre>
<p>With <code>standalone</code> support you can get rid of the <code>AppModule</code> entirely by turning the <code>standalone</code> property on your <code>AppComponent</code> to be <code>true</code></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { CommonModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common'</span>

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-root'</span>,
  standalone: <span class="hljs-literal">true</span>,
  imports: [ CommonModule],
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./app.component.css'</span>]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent {
  title = <span class="hljs-string">'ng14'</span>;
}
</code></pre>
<p>This single property will make your component more self-reliant in terms of declaring what they need to operate. As <code>app.module.ts</code>  is not needed anymore, the work it used to do becomes the responsibility of your standalone components. A standalone component should declare everything, all the common Angular provided feature it needs in the <code>imports</code> array.</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
  <span class="hljs-comment">// ...</span>
  standalone: <span class="hljs-literal">true</span>,
  imports: [
        CommonModule, 
        RouterModule, 
        SomeCommunityModule, 
        SomeStandaloneComponent, 
        SomeStandaloneDirective, 
        SomeStandalonePipe
    ],
  templateUrl: <span class="hljs-string">'./your-standalone.component.html'</span> 
  <span class="hljs-comment">// can use features made available by above imports like  `*ngIf`, `routerLink`, etc.</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> StandaloneComponent {
}
</code></pre>
<p>Similar to standalone modules, you can have standalone pipes and directives working on the same <code>standalone</code> premise.</p>
<h3 id="heading-bootstrapping-with-standalone-components">Bootstrapping with Standalone Components</h3>
<p>Since your application, is now a standalone component(not a module) right from the root/top you’re not required to bootstrap the old way. You use <code>bootstrapApplication</code> from <code>@angular/platform-browser</code> to kickstart booting your <code>AppComponent</code> . The <code>bootstrapApplication</code> takes the root standalone component as an argument</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { bootstrapApplication } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;

<span class="hljs-keyword">import</span> { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app/app.component'</span>
<span class="hljs-keyword">import</span> { environment } <span class="hljs-keyword">from</span> <span class="hljs-string">'./environments/environment'</span>;

<span class="hljs-keyword">if</span> (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent)
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));
</code></pre>
<p>With <code>ngModule</code> left redundant, and <code>imports</code> being owned by the standalone entities, you’d wonder how providers could be made available to your root component and all its children. This is where the second parameter to <code>bootstrapApplication</code> comes into picture. </p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { enableProdMode, importProvidersFrom } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { bootstrapApplication } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { HttpClientModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>

<span class="hljs-keyword">import</span> { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app/app.component'</span>
<span class="hljs-keyword">import</span> { environment } <span class="hljs-keyword">from</span> <span class="hljs-string">'./environments/environment'</span>;

<span class="hljs-keyword">if</span> (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
    providers: [
        importProvidersFrom(HttpClientModule)
    ]
})
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));
</code></pre>
<p> <em>**</em><code>importProvidersFrom</code> is a special function(only available to <code>bootstrapApplication</code>) that lets you extract providers from the provided module. You can use it to provide providers from <code>HttpClientModule</code>, or <code>RoutingModule</code> or any module provider you’d like to make available application-wide. </p>

💡 <code>BrowserModule</code> <strong>providers are automatically included when you use <code>bootstrapApplication</code>.</strong>



<p>With <code>app.module</code> left redundant you can now remove it, or If you want to incrementally adopt standalone features, keep the <code>app.module.ts</code> and instead of providing the <code>AppComponents</code> in declaration put it just inside the <code>imports</code> array of the <code>AppModule</code></p>
<pre><code class="lang-ts">NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, YourStandaloneComponent ], <span class="hljs-comment">// &lt;---</span>
  bootstrap: [AppComponent]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<h3 id="heading-working-with-routes">Working with Routes</h3>
<p>With the concept of <code>app.module</code> gone, you can define routes inside your standalone components or route specific <code>*.route|routing.ts</code>, whatever fits your project needs.</p>
<p>Say that you want to render a list of notes on the <code>/notes</code> route, you can configure it by providing </p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppRoutes: Routes = [{
    path: <span class="hljs-string">'notes'</span>,
    component: NoteListComponent
}]
</code></pre>
<p>in the <code>app.component.ts</code> and use it in the <code>main.ts</code> by doing the following changes</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { enableProdMode, importProvidersFrom } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { bootstrapApplication } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { HttpClientModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>

<span class="hljs-keyword">import</span> { AppComponent, AppRoutes } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app/app.component'</span>
<span class="hljs-keyword">import</span> { environment } <span class="hljs-keyword">from</span> <span class="hljs-string">'./environments/environment'</span>;
<span class="hljs-keyword">import</span> { RouterModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;

<span class="hljs-keyword">if</span> (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
    providers: [
        importProvidersFrom(HttpClientModule),
        importProvidersFrom(RouterModule.forRoot(AppRoutes))
    ]
})
  .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(err));
</code></pre>

ℹ️ <strong>Providers of the top-level routes need to be extracted and provided while bootstrapping for routing to behave properly.</strong>



<h3 id="heading-lazy-loading-components">Lazy loading components</h3>
<p>The structure we used before paves way for lazy loading. Since it’s components not modules as the root entity, we have a very aptly named <code>loadComponent</code> that marks components to be lazy loaded when visited. The previous structure can be re-written as </p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppRoutes: Routes = [{
    path: <span class="hljs-string">'notes'</span>,
    children: [
        {
            path: <span class="hljs-string">''</span>,
            loadComponent: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./note-list/note-list.component'</span>).then(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> m.NoteListComponent)
        },
        {
            path: <span class="hljs-string">':id'</span>,
            loadComponent: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./note/note.component'</span>).then(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> m.NoteComponent)
        }
    ]
}]
</code></pre>
<p>As you can see, we’re neither required to maintain a module to associate routing definitions, or use <code>loadChildren</code> and it greatly simplifies the routing configuration. <code>loadChildren</code> isn’t made redundant but comes handy when you need to load multiple routes lazily.</p>
<pre><code class="lang-ts">{ 
  path: <span class="hljs-string">'notes'</span>,
  loadChildren: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./note.routes'</span>).then(<span class="hljs-function"><span class="hljs-params">c</span> =&gt;</span> c.noteRoutes)
}
</code></pre>
<p>If you want to configure route-level providers, that’s as easy as configuring the route-level <code>providers</code> array parallel to the <code>path</code> and <code>load</code> properties. Route definition support nesting, and can be described as they used to be described previously.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> noteRoutes: Routes = [
  { 
    path: <span class="hljs-string">''</span>,
    pathMatch: <span class="hljs-string">'prefix'</span>,
    providers: [ NoteService ], <span class="hljs-comment">// &lt;-- include providers here...</span>
    children: [
        {
            path: <span class="hljs-string">''</span>,
            component: NoteListComponent
        },
        {
            path: <span class="hljs-string">':id'</span>,
            component: NoteComponent
        }
    ]
  }
];
</code></pre>
<h3 id="heading-cli-support">CLI Support</h3>
<p>You can easily generate standalone components(or pipe, directives) using the <code>--standalone</code> flag as follows</p>
<pre><code class="lang-ts">ng g component|pipe|directive --standalone your-sa[c/p/d]
</code></pre>
<p>or enable it in schematics, for having all components standalone</p>
<pre><code class="lang-ts"><span class="hljs-string">"schematics"</span>: {
  <span class="hljs-string">"@schematics/angular:component"</span>: {
    <span class="hljs-string">"standalone"</span>: <span class="hljs-literal">true</span>
  }
}
</code></pre>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Standalone components are a breath of fresh air and simplify the mental model of an Angular app’s structure. It brings Angular closer to how components are seen and managed in other modern frontend frameworks and opens ways for the community to contribute more towards embracing tooling that can directly work with more self-contained entities. This modern change,  paves a way to innovate more in the Angular ecosystem, and lays the foundation for pretty exciting changes like <a target="_blank" href="https://dev.to/angular/component-first-architecture-with-angular-and-standalone-components-3pjd">component-first architecture</a> and integration with tooling beyond Webpack <a target="_blank" href="https://github.com/vitejs/vite/issues/543">a bit less frustrating affair.</a> <strong>Read more about Standalone APIs RFC <a target="_blank" href="https://github.com/angular/angular/discussions/45554">here</a> and <a target="_blank" href="https://blog.angular.io/an-update-on-standalone-components-ea53b4d55214">here</a>.</strong></p>
]]></content:encoded></item><item><title><![CDATA[ES 2021 - Meet the New Additions to the Browser Near You]]></title><description><![CDATA[Know about the new additions to the most popular language on the planet]]></description><link>https://aalam.hashnode.dev/es6-2021-new-additions</link><guid isPermaLink="true">https://aalam.hashnode.dev/es6-2021-new-additions</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><dc:creator><![CDATA[Aftab Alam]]></dc:creator><pubDate>Fri, 25 Jun 2021 19:00:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624648212537/9AkHpkwnr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>ES 2021 got standardized few days back(22nd June), and it now supports few really exciting features that contribute towards improving the readability of the language syntax as well as add to the construct repertoire available to deal with string replacement, asynchronicity, and performance.</p>
<p>Let's see what these new additions are!</p>
<h2 id="string-replaceall">String <code>replaceAll()</code></h2>
<blockquote>
<p>or, one method to replace `em all! 💪</p>
</blockquote>
<p>Javascript has long needed a way to replace all the occurrences of a string with provided string, and this method does exactly what we already expect by its name.</p>
<p>Although, javascript has a <code>String.prototype.replace</code> method it can only replace the first occurrence.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> str = <span class="hljs-string">"Mandalorian knows Mandorian, but Mandorians dont know Mandalorian"</span>;
<span class="hljs-keyword">const</span> updatedStr = str.replace(<span class="hljs-string">"Mandalorian"</span>, <span class="hljs-string">"Bobba"</span>)

<span class="hljs-built_in">console</span>.log(updatedStr); <span class="hljs-comment">// Bobba knows Mandorian, but Mandorian dont know Mandalorian</span>
</code></pre>
<p>If we need to carry out <strong>full</strong> <strong>replacement</strong>  we'll have to express the match value as a regular expression</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> str = <span class="hljs-string">"Mandalorian knows Mandorian, but Mandorians dont know Mandalorian"</span>;
<span class="hljs-keyword">const</span> updatedStr = str.replace(<span class="hljs-regexp">/Mandalorian/g</span>, <span class="hljs-string">"Bobba"</span>)

<span class="hljs-built_in">console</span>.log(updatedStr); <span class="hljs-comment">// Bobba knows Mandorian, but Mandorians dont know Bobba</span>
</code></pre>
<p>With <code>String.prototype.replaceAll</code> we now can carry out a full replacement without relying on regex patterns</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> str = <span class="hljs-string">"Mandalorian knows Mandorian, but Mandorians dont know Mandalorian"</span>;
<span class="hljs-keyword">const</span> updatedStr = str.replaceAll(<span class="hljs-string">"Mandalorian"</span>, <span class="hljs-string">"Bobba"</span>)

<span class="hljs-built_in">console</span>.log(updatedStr); <span class="hljs-comment">// Bobba knows Mandorian, but Mandorians dont know Bobba</span>
</code></pre>
<h2 id="promises-promiseany">Promise's <code>Promise.any</code></h2>
<blockquote>
<p>or, just gimme what resolves first! 💨</p>
</blockquote>
<p><code>Promise.any</code> is polar opposite of <code>Promise.all</code>, and it prioritizes the promise that resolves first, and could compensate for latency in scenarios with multiple independent parts where the success of one participant promise is all that's needed. Unlike <code>Promise.all</code> it does not waits for the fulfilment of all participating promises or first rejection to resolve to let the dependent code act. For the following promises that resolve at different times.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fetchTheMando = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(
    <span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"The Mandalorian is here now!"</span>),
    <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>)
  );
});
<span class="hljs-keyword">const</span> fetchBobba = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(
    <span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Bobba Fett is here now!"</span>),
    <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>)
  );
});
<span class="hljs-keyword">const</span> fetchLuke = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(
    <span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"Luke Skywalker is here now!"</span>),
    <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>)
  );
});
</code></pre>
<p>it could be simply used like</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Fetch one and save the child!</span>
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.any([ fetchTheMando, fetchBobba, fetchLuke ]);
  <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Prints "The Mandalorian/Boba Fett/Luke Skywalker is here now!" for whatever promise resolves first</span>
})();
</code></pre>
<p>When any of the participant promises fail, you get a <code>AggregateError</code> that could be handled in a try/catch block like other exceptions.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> fetchTheMando = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(
    <span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">"The Mandalorian is here now!"</span>),
    <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>)
  );
});

<span class="hljs-keyword">const</span> fetchMoff = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> reject());

<span class="hljs-keyword">try</span> {
  (<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.any([ fetchTheMando, fetchMoff ]);
  })();
} <span class="hljs-keyword">catch</span>(error) {
  <span class="hljs-built_in">console</span>.log(error.errors);
}
</code></pre>
<ul>
<li><code>Promise.any</code> is similar to <code>Promise.race</code>, except it, doesn’t reject early when one of the promises rejects.</li>
</ul>
<h2 id="logical-assignment-operator">Logical Assignment Operator</h2>
<blockquote>
<p>or, I ❤️  shorter short-cuts!</p>
</blockquote>
<p>If expressing a condition like <code>x &amp;&amp; x = y</code> or <code>if (x) { x = y }</code> feels verbose, repetitive, or tiring to you the logical assignment operators will prove to be a good friend. You can express the aforementioned expressions simply as <code>x &amp;&amp;= y</code> now. The new syntax combines the logical operations(&amp;&amp;, || or ??) with assignment.</p>
<p>What's more amazing is that this feature extends beyond logical and <code>&amp;&amp;</code> to logical OR <code>||</code> and the Nullish Coalescing operator <code>??</code> too. Let's see how these could be applied.</p>
<p>Logical AND <code>&amp;&amp;</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">2</span>;

<span class="hljs-comment">// pre-ES 2021</span>
x = x &amp;&amp; y

<span class="hljs-comment">// Now</span>
x &amp;&amp;= y; <span class="hljs-comment">// x will be 2</span>
</code></pre>
<p>Logical OR <code>||</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">2</span>;

<span class="hljs-comment">// pre-ES 2021</span>
x = x || y;

<span class="hljs-comment">// now...</span>
x ||= y; <span class="hljs-comment">// x will be 2 as the assignment will only happen when x is falsy</span>
</code></pre>
<p>Null Coalescing <code>??</code></p>
<pre><code class="lang-js">
<span class="hljs-keyword">let</span> x;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">2</span>;

<span class="hljs-comment">// pre-ES 2021</span>
x = x ?? y;

<span class="hljs-comment">// now...</span>
x ??= y; <span class="hljs-comment">// as x is undefined, x will be 5 post this</span>
</code></pre>
<h2 id="numeric-separators">Numeric Separators</h2>
<blockquote>
<p>or, I luv 🔢 neat!</p>
</blockquote>
<p>Underscore(_) as separators has been available in many programming languages, and can greatly improves the readability in representing numeric and <code>bigint</code> values. Here's how you can use it</p>
<pre><code class="lang-js"><span class="hljs-comment">// pre-ES 2021</span>
<span class="hljs-keyword">const</span> bounty = <span class="hljs-number">1000000000</span>; <span class="hljs-comment">// Is this a billion? a hundred million? Ten million?</span>

<span class="hljs-comment">// now...</span>
<span class="hljs-keyword">const</span> bounty = <span class="hljs-number">1</span>_000_000_000_000; <span class="hljs-comment">// neat!</span>
</code></pre>
<p>this can be applied to binary</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> beskar = <span class="hljs-number">0b1010</span>_0001_1000_0101;
</code></pre>
<p>and hex literals too</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> messageFromMarshal = <span class="hljs-number">0xA0</span>_B0_C0;
</code></pre>
<h2 id="weakref-and-finalizationregistry">WeakRef and FinalizationRegistry</h2>
<blockquote>
<p>or, I like being 🧠 mindful towards memory!</p>
</blockquote>
<p><code>WeakRef</code> and <code>FinalizationRegistry</code> serve two functions</p>
<ul>
<li>creation of weak references to objects with the <code>WeakRef</code> class</li>
<li>running user-defined finalizers after objects are garbage-collected</li>
</ul>
<p>and could be used independently or together, depending on the use-case.</p>
<p>A  <code>WeakRef</code> (<em>weak reference)</em> to an object is a reference that won't prevent the object it refers to, from being garbage collected. Even, when garbage collector sees the referred object referenced in a non-collectible path.</p>
<p>Consider the following code</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mandoCalls = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> starWarsGalaxy = {
    <span class="hljs-attr">entities</span>: {
            <span class="hljs-attr">mando</span>: {
                <span class="hljs-attr">title</span>: <span class="hljs-string">"lone bounty hunter"</span>,
                <span class="hljs-attr">bio</span>: <span class="hljs-string">"travels in the outer reaches of the galaxy, far from the authority of the New Republic"</span>
            },
            ...
        },
        <span class="hljs-attr">travels</span>: {
            ...
        }
  };
  <span class="hljs-built_in">console</span>.log(starWarsGalaxy);
}

(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      mandoCalls();
      resolve();
    }, <span class="hljs-number">2000</span>);
  });
})();
</code></pre>
<p>When the above code is executed, <code>starWarsGalaxy</code> will be printed after 2 seconds. Based on how we use the <code>mandoCalls</code> , <code>starWarsGalaxy</code> may remain stored in memory forever.</p>
<p>A <code>WeakRef</code> will let you declare this object as a weak reference, and makes it ephemeral in a non-predictable world.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mandoCalls = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> starWarsGalaxy = <span class="hljs-keyword">new</span> WeakRef({
    <span class="hljs-attr">entities</span>: {
            ...
        },
        <span class="hljs-attr">locations</span>: {
            ...
        }
  });
  <span class="hljs-built_in">console</span>.log(starWarsGalaxy.deref());
}

(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      mandoCalls(); <span class="hljs-comment">// Guaranteed to print starWarsGalaxy entries</span>
      resolve();
    }, <span class="hljs-number">2000</span>);
  });

  <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      mandoCalls(); <span class="hljs-comment">// No Gaurantee that starWarsGalaxy is still attached</span>
      resolve();
    }, <span class="hljs-number">4000</span>);
  });
})();
</code></pre>
<p>Use of the <em>target</em> or <em>referent</em> object <code>starWarsGalaxy</code> is guaranteed to work as expected in the first <code>mandoCalls</code> but has zero chances of yielding in the subsequent calls. As <em>referents</em> are wrapped in a <code>WeakRef</code> , their access approach also changes to <code>referent.deref()</code> instead of direct access.</p>
<p><code>WeakRef</code> prove useful in implementing cache or mappings to large objects where you'd not prefer to hold the referent objects too long after use.</p>
<p><code>FinalizationRegistry</code> as a companion feature lets you listen to garbage collection on objects you're interested in.</p>
<p>Once you have a <code>FinalizationRegistry</code> instance, with a cleanup callback</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> registry = <span class="hljs-keyword">new</span> FinalizationRegistry(<span class="hljs-function">(<span class="hljs-params">heldValue</span>) =&gt;</span> {
  <span class="hljs-comment">// do something with the held value</span>
});
</code></pre>
<p>You can register the objects you'd like the callback to be executed for (post garbage collection) with the <code>register</code> method</p>
<pre><code class="lang-js">registry.register(theInterestingObject, <span class="hljs-string">"pass this on as the held value!"</span>);
</code></pre>
<p>Execute something like</p>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> starWarsGalaxy = {};

  registry.register(starWarsGalaxy, <span class="hljs-string">"Bobba says bye"</span>);
})();
</code></pre>
<p>and the passed message <code>Bobba says bye</code> will be received by the cleanup callback, registered while instantiating <code>FinalizationRegistry</code>  as soon as <code>starWarsGalaxy</code> is garbage collected.</p>
<h3 id="conclusion">Conclusion</h3>
<p>You might not find immediate use for these new additions, but they're noteworthy enhancements from a language maturity point of view. All of these features are <a target="_blank" href="https://caniuse.com/?feats=mdn-javascript_builtins_string_replaceall,mdn-javascript_builtins_promise_any,mdn-javascript_builtins_weakref,mdn-javascript_operators_logical_or_assignment,mdn-javascript_operators_logical_and_assignment,mdn-javascript_operators_logical_nullish_assignment,mdn-javascript_grammar_numeric_separators">available to the evergreen browsers</a> <a target="_blank" href="https://v8.dev/features/tags/es2021">near you</a>, and could be easily configured with babel for use.</p>
]]></content:encoded></item></channel></rss>