<?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 Anjali Tanpure on Medium]]></title>
        <description><![CDATA[Stories by Anjali Tanpure on Medium]]></description>
        <link>https://medium.com/@tanpure-anjali?source=rss-ab91b1950965------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kqaXBwuLAX8Mj56AlfI0SQ.jpeg</url>
            <title>Stories by Anjali Tanpure on Medium</title>
            <link>https://medium.com/@tanpure-anjali?source=rss-ab91b1950965------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 16:24:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanpure-anjali/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[Compilation in Angular Part-II]]></title>
            <link>https://tanpure-anjali.medium.com/compilation-in-angular-part-ii-7a6bdb04723a?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a6bdb04723a</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[compilation]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 09:38:48 GMT</pubDate>
            <atom:updated>2023-02-20T09:38:48.852Z</atom:updated>
            <content:encoded><![CDATA[<h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cakGc65GZ7cdLHgME62Asg.jpeg" /></figure><p>Hello everyone! You must have gone though the part-I of this article which is, <a href="https://medium.com/p/a9cf81ac79e">Compilation in Angular Part-I</a>, where we understood two modes of compilation AOT and JIT. In subsequent parts, we will understand more on how the compiler works. First let’s get started with the architecture of compilation.</p><h3>How is the Compiler Set Up ?</h3><p>We need to understand how the compiler is set up since it will help us to understand how TypeScript actually works under the hood as our compiler is based on TypeScript(TS).</p><p>The regular TS compiler is based on three phases: Program creation, Type-checking &amp; Emit phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*KAFG5IrWCeUA9iFog_X1Mg.png" /><figcaption>Regular TS Compiler Phases</figcaption></figure><p>And Angular compiler has built on top of that, adding two more phases: an Analysis step and Resolve step. Let’s understand these steps one by one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*V6Rn9p5sozpYzjAYYhh7Iw.jpeg" /><figcaption>Angular Compiler Phases</figcaption></figure><p><strong>1] Program Creation</strong></p><p>Here, TS find outs all the source files which are required to understand our program &amp; it begins with tsconfig.json file. It recursively find imports of those and discover more files might be from app/other libs imported from node modules unti it’s seen all the code it needs to see the types in our program &amp; checks them correctly.</p><p>In case with Angular we add into this process a little bit by adding some extra files that are not necessarily we write and that’s why it’s possible to import the factory files.</p><p><strong>2] Analysis</strong></p><p>In this step, it’s taking the full set of files from our code &amp; looking through all the classes in them and trying to find out the ones which are decorated with the Angular decorators. Then it tries to understand what the parts of our application are, the components, the modules, the services, the directives and so on in isolation. If it’s a component, it will parse the template, likewise.</p><p>During the analysis phase, it is only looking at these classes on a one-by-one basis.</p><p><strong>3] Resolve</strong></p><p>After analysis is complete, after seeing all the classes, the resolve phase comes into the picture. Here it looks into everything again but with the larger picture. So when it looks at the component, it understands what module it belongs to. And through this it can make more global decisions &amp; optimisations based on that. Also surface the errors related to the structure of the application.</p><p><strong>4] Type-checking</strong></p><p>This step is mostly for validations. It asks TypeScript to check on any errors in the program, the errors in the Angular templates. And this is done via code generation.</p><p><strong>5] Emit</strong></p><p>During this phase, the TS code goes through a series of transformations. And it merges down the line as downlevel JavaScript(JS) code that is ready to run in the browser. In this step, as it’s emitting JS code for each class, it’s also adding to it any of the imperative Angular code that we are generating if that class needs it. So we’re adding all the template functions to the components and other things like that.</p><p>This is most expensive step in compilation — translating TS code to JS.</p><p>These five phases describe at a high level what happens every time we invoke the Angular compiler. But every Angular application actually depends on running the compiler not just once but many times.</p><p>In the next article we will see about a ‘Compilation Model’ in brief. <br>Thanks for reading. Stay tuned !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a6bdb04723a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compilation in Angular Part-I]]></title>
            <link>https://tanpure-anjali.medium.com/compilation-in-angular-part-i-a9cf81ac79e?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9cf81ac79e</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jit]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[compilation]]></category>
            <category><![CDATA[aot]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 06:52:06 GMT</pubDate>
            <atom:updated>2023-02-20T09:06:28.148Z</atom:updated>
            <content:encoded><![CDATA[<h4>Need and Methods</h4><p>Hello everyone! As most programming language use a compiler, so in this blog series we are going to understand how compilation works in Angular, it’s architecture, features, types, compilation model etc. In the part-I we will understand why Angular needs a compiler and it’s type on a high level, and in upcoming articles we will cover further points and understand more about it.</p><p>In a simple language,</p><blockquote>A compiler is a special program that translates a programming language’s source code into machine code or another programming language.</blockquote><p><strong>Why does Angular have a compiler ?</strong></p><p>The main job of a compiler is to translate the template we write into the code that runs at runtime. In Angular we write the templates declaratively, we specify what should happen, the components, selector for that component, the bindings etc, but not how it should happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*3iX9N5GvWfdqjiwHBRZ9GQ.png" /><figcaption>Declarative Syntax</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*sNsjriWtopkf8Gf2ojsEGQ.png" /><figcaption>Imperative Syntax</figcaption></figure><p>Browsers however do not understand declarative Angular syntax. So we have to change it to something that the browser can understand. Then the question in your mind might arise, if this imperative code is needed anyway, why do we not directly write the code the browser can understand, and save the trouble of going through the compiler entirely ?</p><p>Reasons:</p><ol><li>Less boilerplate, the less we have to think about how things work under the hood, how it renders, the more time we can focus on business logic.</li><li>Optimize the things, the code, the time.</li></ol><p>So the compiler’s job is, to take declarative Angular instructions, both the templates &amp; decorators that we write and translate them into imperative code. In short, the compilation in Angular meaning, converting the Angular code into plain JavaScript.</p><h3><strong>Compilation Methods in Angular</strong></h3><p>Our compiler can do this transformation in one of two different ways:</p><ol><li>JIT (Just In Time)</li><li>AOT (Ahead Of Time)</li></ol><p><strong>Just In Time Compilation (JIT)</strong></p><p>This is used in development mode of Angular. When we build an application in JIT mode, we take TypeScript code &amp; compile using TypeScript compiler(tsc) and it gets translated into JS code. But here, all of the angular decorators that we have written actually end up in that bundled JS and they run in the browser. When those decorators execute in the browser, it calls our compiler and translates our templates, other Angular features into imperative code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*XKQsEcAk975H22jiBxAcJg.png" /><figcaption>JIT</figcaption></figure><p><strong>Ahead Of Time (AOT)</strong></p><p>In this mode instead of running plain TypeScript compiler, it runs Angular compiler(ngc). Now let’s understand what is the difference between tsc and ngc compilers. ngc does the same thing as tsc compiler, it takes TS code and translates it into JS, <strong>but also it takes the Angular decorators</strong> <strong>which we have written &amp; pre-compiled them into the imeprative instructions to render in a browser</strong>. So it would save the cost and time to compile those decorators at runtime unlike JIT. It also detects and reports template binding errors during the build steps before users can see them.</p><p>The compilation type JIT or AOT depends on the value of the aot property in the build configuration specified in angular.json. By default, aot is set to true from Angular-9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*PUv6q59Ak5SWY19-7EueMg.jpeg" /><figcaption>AOT</figcaption></figure><p><strong>JIT vs AOT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*mnxFX_PDgxVUq_wQdVAG7Q.png" /></figure><p>I hope these contents are helpful to understand the compiler, Angular compiler, JIT vs AOT. In the next blog, we will understand the architecture and features of the compiler.</p><p>Thanks for reading. Stay tuned !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9cf81ac79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Execution Context Creation & Hoisting]]></title>
            <link>https://medium.com/js-essentials/execution-context-creation-hoisting-935fa11f4035?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/935fa11f4035</guid>
            <category><![CDATA[execution-context]]></category>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js-essentials]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 10:27:56 GMT</pubDate>
            <atom:updated>2021-09-27T10:27:56.502Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi all ! In the last post of <a href="https://medium.com/js-essentials">JS Essentials</a> we have learnt about, <a href="https://medium.com/js-essentials/the-global-object-global-environment-4a59bec944cd">The Global Object &amp; Global Environment</a>. In this post we will be learning about execution context creation and hoisting.</p><p>To understand how JavaScript creates an execution context, first we need to understand the term ‘Hoisting’. Look at the below example:</p><pre>fun();<br>console.log(greet);</pre><pre>function fun() {<br> console.log(“fun() called!”);<br>}</pre><pre>var greet = “Hello World!”;</pre><p>What output would you expect ? In most of the programming languages, we will consider this as an error, since it executes the code line by line &amp; one line at a time. Since on the very first line there is a method called fun(), which is not defined yet. But JavaScript does not work like that. When you execute above lines of code, it will generate output as:</p><pre>fun() called!<br>undefined</pre><p>So even though the function was below the calling, it still ran. And the variable ‘greet’ is available on the second line, though it doesn’t have a proper value, but that variable somewhere is declared on that file. Now, if we do not define the variable ‘greet’ at all, then our compiler will throw an error as : “Uncaught ReferenceError: greet is not defined”. And this phenomenon is called <strong>‘Hoisting’.</strong></p><p>But don’t be under the <strong>wrong impression</strong> the way it is explained, means, in most of the websites it’s explained as — In JS, variables &amp; functions are hoisted and moved to the top by JavaScript engine, as if they moved physically up to the top. It’s not like var greet = “Hello World!”; copied and moved at the top.</p><p>In JS, the variables &amp; functions are to some degree available even though they’re written later in the code. To understand what JS is doing here, we need to understand the <strong>execution context</strong> and how it is created.</p><p>The execution context is created in two phases, the first phase is called the <strong>Creation Phase. </strong>In this phase we know, we have the <strong>‘global object’</strong> &amp; <strong>‘this’</strong> which is set up within the memory that we have already seen in my past posts. Apart from that there is an <strong>outer environment</strong>. In this phase, the parser runs through the code and begins to set up what we have written for translation, it recognises where we have created variables &amp; functions. In creation phase, it sets up the memory space for the variables &amp; functions, and this step is called ‘Hoisting’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*wq5tve41gsxMPwmGeRvrfw.png" /></figure><blockquote>Before the code begins to be executed line by line, the JavaScript engine has already set aside memory space for the variables and functions that we have created in that entire code we have built.</blockquote><p>So those functions &amp; variables exist in the memory, so when code executes line by line, it can access them. But functions entirely placed into the memory, means the function — it’s name and code inside the function is being executed.</p><p>The next phase of execution context is execution phase, where it actually executes the code line by line, and variables/functions assignments are set, example: var a equals to 3. So in creation phase, when the JS engine sets up the memory space for variable ‘a’, it doesn’t know it’s value at that time, so it puts the placeholder there called <em>‘</em><strong><em>undefined</em></strong><em>’. </em>It means oh, I don’t know what this value is yet.</p><p>I hope hoisting is now clear, we will more talk about the ‘undefined’ in next post. Thanks for the reading !</p><p><strong>Conclusion:</strong></p><ul><li>Execution context has two phases: Creation and Execution phase.</li><li>All variables in JavaScript are initially set to ‘undefined’. And functions are entirely sitting in the memory at creation phase. This is hoisting.</li></ul><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935fa11f4035" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-essentials/execution-context-creation-hoisting-935fa11f4035">Execution Context Creation &amp; Hoisting</a> was originally published in <a href="https://medium.com/js-essentials">JS Essentials</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement Google Recaptcha v3 in Angular]]></title>
            <link>https://tanpure-anjali.medium.com/how-to-implement-google-recaptcha-v3-in-angular-2a4fd026f4ab?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a4fd026f4ab</guid>
            <category><![CDATA[google-recaptcha]]></category>
            <category><![CDATA[recaptcha-v3]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[recaptcha]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Mon, 24 May 2021 14:52:33 GMT</pubDate>
            <atom:updated>2021-05-25T04:06:38.835Z</atom:updated>
            <content:encoded><![CDATA[<p>While using any web application, when user creates a new account, post a comment on some website or buy something, came across different type of captcha like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*5kaPMxO2svjJ5k34zOwmrg.png" /></figure><h3>What is reCaptcha ?</h3><p><strong>CAPTCHA</strong> stands for the <strong>C</strong>ompletely <strong>A</strong>utomated <strong>P</strong>ublic <strong>T</strong>uring test to tell <strong>C</strong>omputers and <strong>H</strong>umans <strong>A</strong>part.</p><blockquote><strong>reCAPTCHA </strong>is a free service that protects a site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.</blockquote><h3>Introducing reCAPTCHA v3</h3><p>The 3rd version of Google’s reCAPTCHA was recently released. It does not have a user interface, also it is completely invisible. It helps us detect abusive traffic on our website. Instead of showing a CAPTCHA challenge, reCAPTCHA v3 returns a score so we can choose the most appropriate action for our website.</p><h3>Implementation in Angular</h3><h4>Step-1: Register Google reCaptcha</h4><p>Visit this link <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a> and register a new site like this:</p><figure><img alt="register v3 key" src="https://cdn-images-1.medium.com/max/585/1*o2VcqbGXoYTBRwckxQ3TFw.png" /></figure><p>Here we have to add a label of your choice, have to select reCAPTCHA v3, specify a domain. If you wanna try locally, add localhost domain. Accept terms &amp; conditions and click on ‘Submit’ button.</p><p>We will get a <strong>secret key</strong> and <strong>site key</strong>. The site key is what we need to implement google recaptcha v3 in the frontend. And a secret key (keep it secret). This will be used for g-recaptcha’s frontend response verification on our backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*99ZPYXvU1-nQE5yXfijdDw.png" /></figure><h4>Step-2: Load the JavaScript API with your sitekey.</h4><pre>&lt;script src=&quot;https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key&quot;&gt;&lt;/script&gt;</pre><h4>Ste — 3: Install angular-recaptcha3 via npm</h4><p>In your project add angular-recaptcha3 via command npm i angular-recaptcha3 — save</p><h4>Step-4: Import ReCaptchaModule</h4><p>Add ReCaptchaModule either in the app module or any specific module where you want to use this feature (register/login). In the forRoot() method mention the RECAPTCHA_OPTION. To know more about different options visit this <a href="https://developers.google.com/recaptcha/docs/display">link</a>.</p><p>Syntax:</p><pre>import { ReCaptchaModule } from &#39;angular-recaptcha3&#39;;<br><br>@NgModule({<br>    imports: [<br>        ReCaptchaModule.forRoot(RECAPTCHA_OPTION)<br>    ]<br>})</pre><pre>const RECAPTCHA_OPTION = {<br>    language?: string;<br>    invisible?: IRecaptchaOption;<br>    normal?: IRecaptchaOption;<br>}<br><br>interface IRecaptchaOption {<br>    sitekey: string;<br>    theme?: string;<br>    type?: string;<br>    tabindex?: number;<br>    badge?: string;<br>}</pre><p>Example: I have added this in login module of my project. Added basic recaptcha options, you can modify them as above.</p><pre>import { ReCaptchaModule } from &#39;angular-recaptcha3&#39;;<br><br>@NgModule({<br>    imports: [<br>        ReCaptchaModule.forRoot({<br>            invisible: {<br>                sitekey: &#39;your key&#39;, <br>            },<br>            normal: {<br>                sitekey: &#39;your key&#39;, <br>            },<br>            language: &#39;en&#39;<br>        }),<br>    ]<br>})</pre><h4>Step-5: Insert the recaptcha in the template to initialize it</h4><p>Recaptcha has different parameters, you can add according to your need: hide, sitekey, size, theme, type, tabindex, badge, language.</p><pre>&lt;recaptcha <br>    [size]=&quot;&#39;invisible&#39;&quot;<br>    [hide]=&quot;false&quot; <br>    (captchaResponse)=&quot;onCaptchaResponse($event)&quot;&gt;<br>&lt;/recaptcha&gt;</pre><h4>Step-6: Get the response token &amp; perform action</h4><p>a. Now either you can implement method onCaptchaResponse() mentioned above to get the response token or you can call recaptchaService.execute()</p><p>b. If you are implementing some button click, example login form’s submit button then you can call the service’s execute() method to get token.</p><pre>import { ReCaptchaService } from &#39;angular-recaptcha3&#39;;</pre><pre>constructor(private recaptchaService: ReCaptchaService) { }</pre><pre>login() {<br> this.recaptchaService.execute({action: ‘login’}).then(token =&gt; {<br>   // Backend verification method<br>   this.sendTokenToBackend(token);<br> });<br>}</pre><h4>Step-7: Now recaptcha is activated !</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*oxMyMpKrmUgk3pvrmn6DGw.png" /></figure><h4>Step-8: Verify recaptcha token on backend side</h4><p>In backend code, we need to call this API to verify the response.<br>URL: <a href="https://www.google.com/recaptcha/api/siteverify">https://www.google.com/recaptcha/api/siteverify</a> <br>METHOD: POST</p><ul><li>If success true we can assume that the user is not a robot, and process whole request</li><li>If not, return error.</li></ul><p>In this way we can implement v3 of reCaptcha in Angular app.<br>Thanks for reading :)</p><h3>References:</h3><ul><li><a href="https://developers.google.com/recaptcha/docs/v3">https://developers.google.com/recaptcha/docs/v3</a></li><li><a href="https://www.npmjs.com/package/angular-recaptcha3">https://www.npmjs.com/package/angular-recaptcha3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a4fd026f4ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Global Object & Global Environment]]></title>
            <link>https://medium.com/js-essentials/the-global-object-global-environment-4a59bec944cd?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a59bec944cd</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[execution-context]]></category>
            <category><![CDATA[global-object]]></category>
            <category><![CDATA[js-essentials]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 07:46:40 GMT</pubDate>
            <atom:updated>2021-03-15T07:57:06.737Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will learn about the global environment &amp; the global execution context. Whenever any code runs in a JS, it runs inside an execution context. It’s an abstract concept, a wrapper where the JS code is executed and evaluated.</p><p>When we are looking at the JS program, we’re going to be looking at an execution context being created and run. Normally there is more than one execution context running during a JS program. The base execution context is the global execution context. When we talk about the word <strong>global</strong>, the thing that is accessible everywhere to everything in our code.</p><p>The global execution context creates two things for us:</p><ol><li>Global Object</li><li>Special variable called — ‘this’</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*-l9dPeAbFoeArjqa320zsw.png" /></figure><p>Now, let’s actually see it. Have created index.html file like this in any code editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*yLtcI-7lqLjhzn5RJuR-Ig.png" /></figure><p>And included an app.js file which is a blank JS file. Now I have run this index.html file in Google Chrome browser and opened the browser’s console &amp; typed ‘this’ &amp; pressed enter like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*C6hSOdBqsnbo9rH1Z4BZmg.png" /></figure><p>Here the JS file was loaded, the syntax parser started &amp; realised there is nothing to parse as our JS file was empty. But because as we ran the file, JS engine started executing and the execution context was created. As we have seen above, as execution context is created, it will create 2 things from us — global object &amp; ‘this’. So though our code was empty, JS engine decided what will be the value of this, and in this case it is the ‘window’ — The current window. Since we are running JS in the browser. So this window object is the current tab that we are on.</p><p>This is the global object inside the browser. If we use node.js this global object will be the different one. But there’s always a global object when we run JS.</p><p>Notice that we have these two values, global object &amp; this even we did not write any actual code. And that is the JavaScript engine doing for us. At the global level those two things are equal.</p><blockquote>Global: The code or variable aren’t inside a function is global.</blockquote><p>Now, let’s check what will happen with some code. So have added one variable with some value assigned to it &amp; one blank function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*r0t9Wz8olzgbDeh4IPmwSw.png" /></figure><p>After running this code: As we have seen execution context is created. Variable is not inside a function. When variables &amp; functions are not inside any function in JS, those get attached to the global object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*CmYc-hpCYRLf26PXwBot4Q.png" /></figure><p>If we type window.greet or simply greet in console, we get “Hello World!” values.</p><p>So when our variables and functions are lexically not sitting inside a function, they’re just sitting right there on a global object.</p><h4>Summary</h4><ul><li>When JavaScript code is executed, an execution context is created.</li><li>At base level, when we are not inside a function, we have a global object that the JS engine creates for us as a part of the execution context.</li><li>If we are running code inside a browser, the global object is the ‘window’ object. ‘this’ will be the ‘window’ object.</li></ul><p>In the next article we will be continuing on the execution context and hoisting. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a59bec944cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-essentials/the-global-object-global-environment-4a59bec944cd">The Global Object &amp; Global Environment</a> was originally published in <a href="https://medium.com/js-essentials">JS Essentials</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Objects in JavaScript]]></title>
            <link>https://medium.com/js-essentials/objects-in-javascript-d7365fbe9487?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7365fbe9487</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[js-essentials]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 08:17:22 GMT</pubDate>
            <atom:updated>2020-12-11T08:17:22.481Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello all! In this article we are talking about objects in JavaScript. To understand JavaScript, we need to understand what are the objects in JavaScript.</p><h3>Objects In Real Life</h3><p>Just like any other programming languages, we can compare objects in real life. Let’s take an example of a car. There are different properties of a car like a car has a colour. It has a model, design, size, weight, engine etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*lu3yptokW1Yj7YoH.png" /></figure><p>So if we look at the properties of above car we can say that:<br>- The <strong><em>model </em></strong>of the car is<strong><em> Honda City</em></strong><br>- The <strong><em>colour </em></strong>is <strong><em>red </em></strong><br>- The <strong><em>engine </em></strong>is <strong><em>1498 cc</em></strong><br>- <strong><em>Transmission type</em></strong> is <strong><em>manual</em></strong><br>- The <strong><em>seating capacity</em></strong> of the car is <strong><em>5<br></em></strong><em>- </em><strong><em>Fuel tank capacity </em></strong>is<strong><em> 40 L</em></strong></p><p>Similarly objects in programming language have some properties and those properties have some value, like the model of the car is Honda City so property name is ‘model’ and value is ‘Honda City’.</p><h3>Name — Value Pair</h3><blockquote>A name which maps to a unique value.</blockquote><p>It means a name has some value. A pair which consists of name and value. The name may be defined more than once but only can have one value in any given execution context. The value may have another name/value pair.</p><p>Note: We will learn about execution context in detail in upcoming posts.</p><p>So in any particular execution context i.e. a section of a code that is running, a name can only exist and be defined with one value.</p><p>Example, firstName =Anjali, here name is ‘firstName’ and value is ‘Anjali’. This is the name-value pair.</p><h3>Objects</h3><p>When we are talking about objects, we can use this name-value pair concept to define them.</p><blockquote>A collection of name-value pairs.</blockquote><p>This is the simplex definition when talking about the objects.</p><pre>student = {<br>    fName: &#39;John&#39;<br>    lName: &#39;Doe&#39;<br>    age: &#39;15&#39;,<br>    address: {<br>        street: &#39;DP Rd&#39;,<br>        flatNo: &#39;401&#39;,<br>        floor: 4<br>    }<br>}</pre><p>Suppose we have a name as ‘student’ and the value is a collection of other name-value pairs. fname is a name &amp; value is ‘John’. lName is a name, value is ‘Doe’. address is a name &amp; value is a collection of other name-value pairs. This is an object in JS.</p><p>So when we are talking about objects, we are talking about <strong>collection of name-value pairs</strong>. We are not going into much details right now. We will cover everything step by step in upcoming articles.</p><p>I hope objects at basic level are cleared now. In the next article we are going to talk about global objects.</p><p>Thank you for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7365fbe9487" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-essentials/objects-in-javascript-d7365fbe9487">Objects in JavaScript</a> was originally published in <a href="https://medium.com/js-essentials">JS Essentials</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lexical Environment]]></title>
            <link>https://medium.com/js-essentials/lexical-environment-315102f7c2f6?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/315102f7c2f6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lexical-environment]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[basic-concept]]></category>
            <category><![CDATA[js-essentials]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 16:04:45 GMT</pubDate>
            <atom:updated>2021-02-03T05:35:56.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello all, I hope you read the first article of JS Essentials i.e. <a href="https://medium.com/js-essentials/syntax-parser-66989c0d504">Syntax Parser</a>. Now let’s proceed further and talk about our next under the hood concept which is ‘Lexical Environment’.</p><p>Let’s first understand what is the meaning of the word ‘lexical’ ? Lexical is nothing but related to words or vocabulary of a language or grammar. A lexical environment is where something sits physically in the code we write. And that environment is created behind the scene. This is the logistic concept &amp; we can’t actually access it from our JS code. Then why do we need to understand it ? Because whenever we are creating any function in JS, we have been creating a lexical environment along with it but we didn’t know it.</p><blockquote>A Lexical environment is where something sits physically in the code we write.</blockquote><p>Let’s take an example to understand it better. Suppose there is a function having one variable inside it.</p><pre> function greet() {<br> var msg = “Hello World”;<br>}</pre><p>We can say that variable ‘msg’ sits lexically inside the function. Just imagine physically where we are writing the code, there it sits. But if you read our last blog post about <a href="https://medium.com/js-essentials/syntax-parser-66989c0d504">Syntax Parser</a>, we said that our code is not actually given directly to the computer, but it translated into something the computer can understand.</p><p>But in programming language, ‘lexical environment’ is important, that means where we see things written gives us an idea of where it will actually sit in the computer’s memory. And how it will interact with other variables, functions and elements of the program. And that’s because the program, the compiler that is converting our code to those instructions cares about where we put things. It makes decisions that syntax parser going through everything makes decisions.</p><p>So when we talk about the lexical environment of something in the code we’re talking about where it’s written &amp; what surrounds it. I hope this post helps to understand one of the the basic terms of JS. I will talk about ‘‘Execution Context’ in upcoming articles. Let me know if you have any queries in the comments section below or on my personal email address. Till that stay tuned ! Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315102f7c2f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-essentials/lexical-environment-315102f7c2f6">Lexical Environment</a> was originally published in <a href="https://medium.com/js-essentials">JS Essentials</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syntax Parser]]></title>
            <link>https://medium.com/js-essentials/syntax-parser-66989c0d504?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/66989c0d504</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[syntax-parser]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js-essentials]]></category>
            <category><![CDATA[javascript-concepts]]></category>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 16:01:25 GMT</pubDate>
            <atom:updated>2021-03-15T05:50:53.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone and welcome to the JS Essentials. This is the platform where we are learning different JavaScript concepts. It is important to know how JS works under the hood to get a better understanding before writing any business logic.</p><p>I have started this series because I just did a course from Udemy by <a href="https://www.udemy.com/user/anthonypalicea/"><strong>Anthony Alicea</strong></a><strong>, ‘JavaScript: Understanding the Weird Parts’. </strong>And he explained it very well right from scratch. You may go through this cource. Most parts I am taking from this course so that everyone can read &amp; understand conceptwise, if do not have time to go through the whole course.</p><p>Let’s begin with one of the most basic and important concepts — Syntax Parser.</p><blockquote>The program that reads our code and determines what it does and if it’s grammar is valid.</blockquote><p>We write code and that code isn’t a magic that computers understand as we write. Computer is not a human being, it has it’s own language. Someone else wrote a program to translate it for the computer. When we write JavaScript code, it isn’t directly asking the computer what to do. Those details are hidden from us. Someone else or there is some other program which converts our JS code into something that the computer can understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*lAOiNPPcvqJaqBEd8Z_kIw.jpeg" /></figure><p>We can take example of human translators, take a look at above example. If person ‘A’ understands only English and person ‘C’ understands only ‘German’, then how can they communicate ? Correct, through ‘translators’ (also known as interpreters) who understands both the languages. In computer language, those programs or translators are called ‘compilers’ &amp; they also have to do with ‘interpreters’.</p><p>But those programs — interpreters &amp; compilers do the process. They actually read our code character by character and determines if syntax is valid and then implements that syntax in a way the computer can understand.</p><p>Suppose we have our code &amp; there is a program that is going to convert what we have written into a real set of computer instructions, something that hardware can physically understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*YeUXWoI30XAc6iAV1qX1vg.jpeg" /></figure><p>If we look at the above example, here we have a JS function with a variable which is represented in the computer’s memory and which is being translated from what we are writing to what the computer can understand. There is a <strong>compiler</strong> or an <strong>interpreter</strong> between those two things &amp; part of that is a <strong>syntax parser</strong>.</p><p>It is going through character by character like F-U-N-C-T-I-O-N and it says oh that’s a ‘function’, so there should be a space after this. And the next thing that it looks up until the parenthesis() will be the ‘name of the function’ etc. And that’s translated by the systems that someone else wrote. But it also means in the translation process, the programmers that wrote the compiler can choose to do extra stuff. Our code is not actually being given to the computer but the translation of it, so the engine that is interpreting our code can decide or choose to do other things also.</p><p>So that’s syntax parser, interpreter between our code and computer which translates our code into machine readable code. And it’s a part of the JavaScript engine that is actually running everytime we run our JS code.</p><p>I hope you enjoy the article with the basic concept of syntax parser. In the next article we are going to talk about lexical environment and execution context. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66989c0d504" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-essentials/syntax-parser-66989c0d504">Syntax Parser</a> was originally published in <a href="https://medium.com/js-essentials">JS Essentials</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Content Projection using <ng-content>]]></title>
            <link>https://tanpure-anjali.medium.com/angular-content-projection-using-ng-content-819106f9e6e1?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/819106f9e6e1</guid>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 17:33:55 GMT</pubDate>
            <atom:updated>2020-08-05T14:23:01.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3csxfuGSpFcxFh2f1C_og.jpeg" /></figure><p>Angular provides lots of features, and one of the most important feature is component reusability. To reuse the components we can use content projection or ng-content. Let’s understand how we can use &lt;ng-content&gt; to reuse the component and project the contents dynamically.</p><p>Let’s take a simple example. Suppose we have two forms as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Ue2vMrPrPQGCtp7qo3SQeg.png" /></figure><p>We want this one to be a ‘Create User’ form &amp; the other one to be a ‘Login’ form. And we just need a different form title and the button text for each of the forms with the same fields i.e ‘Email Address’ &amp; ‘Password’. So it’s not a good practice to create two separate forms/components. Then using a single form/component how can we solve this problem ?</p><p>Here we can use content projection to change a piece of form. Let’s see how we can do this ? Look at the code below:</p><pre>&lt;auth-form (submitted)=”createUser($event)”&gt;&lt;/auth-form&gt;</pre><pre>&lt;auth-form (submitted)=”loginUser($event)”&gt;&lt;/auth-form&gt;</pre><p>For both Login and Create Account forms we are using the same selector of AuthFormComponent. If we look at the template code:</p><pre>&lt;form #form=”ngForm” (ngSubmit)=”onSubmit(form.value)”&gt;<br> &lt;h3&gt;My Form&lt;/h3&gt;<br> <br> &lt;div class=”form-group”&gt;<br>  &lt;label for=”email”&gt;Email Address:&lt;/label&gt;<br>  &lt;input type=”text” class=”form-control” id=”email”&gt;<br> &lt;/div&gt;</pre><pre> &lt;div class=”form-group”&gt;<br>  &lt;label for=”password”&gt;Password:&lt;/label&gt;<br>  &lt;input type=”password” class=”form-control” id=”pwd”&gt;<br> &lt;/div&gt;</pre><pre> &lt;button mat-button color=”success”&gt;Save&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Using this code it will render the forms the same as above images. Now we want the title to be ‘Create Account’ for one form and ‘Login’ to another instead ‘My Form’. So this is where the content projection is useful. We need to pass pieces of information in between these component tags, like this:</p><pre>&lt;auth-form (submitted)=&quot;createUser($event)&quot;&gt;<br>  <strong>&lt;h3&gt;Create Account&lt;/h3&gt;</strong><br>&lt;/auth-form&gt;<br>&lt;auth-form (submitted)=&quot;loginUser($event)&quot;&gt;<br>  <strong>&lt;h3&gt;Login&lt;/h3&gt;</strong><br>&lt;/auth-form&gt;</pre><p>But if we do only this much part it’s not going to work. So what we need to actually do is, project the content through something called as <strong>ng-content</strong>. We need to replace form title which we are showing using &lt;h3&gt; tag in auth component with &lt;ng-content&gt; like this:</p><pre>&lt;form #form=”ngForm” (ngSubmit)=”onSubmit(form.value)”&gt;<br> <strong>&lt;ng-content&gt;&lt;/ng-content&gt;</strong><br> <br> &lt;div class=”form-group”&gt;<br>  &lt;label for=”email”&gt;Email Address:&lt;/label&gt;<br>  &lt;input type=”text” class=”form-control” id=”email”&gt;<br> &lt;/div&gt;</pre><pre> &lt;div class=”form-group”&gt;<br>  &lt;label for=”password”&gt;Password:&lt;/label&gt;<br>  &lt;input type=”password” class=”form-control” id=”pwd”&gt;<br> &lt;/div&gt;</pre><pre> &lt;button mat-button color=”success”&gt;Save&lt;/button&gt;<br>&lt;/form&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*gZx3-CO76kG84zOb6Q2WKg.png" /></figure><p>In the browser’s console we can see that the content has been projected inside our forms. See the below image for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Gpil8LVg9pEJEXpzzrQ-Ng.png" /></figure><p>Ok! Now what if we have multiple contents to project dynamically within a single form?</p><h3>Projection slots with ng-content</h3><p>Now our next use case is we want to inject different buttons based on form. For example, we want button text as ‘Sign Up Free’ for create account form &amp; ‘Login’ for login form instead of ‘Save’.</p><p>To do this we need to add a button like we did to show dynamic form title:</p><pre>&lt;auth-form (submitted)=&quot;createUser($event)&quot;&gt;<br>  &lt;h3&gt;Create Account&lt;/h3&gt;<br>  <strong>&lt;button type=&quot;submit&quot;&gt;Sign Up Free&lt;/button&gt;</strong><br>&lt;/auth-form&gt;<br>&lt;auth-form (submitted)=&quot;loginUser($event)&quot;&gt;<br>  &lt;h3&gt;Login&lt;/h3&gt;<br>  <strong>&lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;</strong><br>&lt;/auth-form&gt;</pre><p>After doing above changes our forms look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*zuU-ar17kloI-MvXP54O9w.png" /></figure><p>Oops! Here we have dynamic buttons as per our need but the placement of buttons are wrong. How can we fix this issue ? So the answer is using content projection slots.<strong> It tells us where to inject each particular piece of information.</strong></p><p>Let’s see how we can do this. First we will remove the extra button ‘Save’ which we can see at the bottom &amp; this is from our common auth component. And instead at that place we can add another ng-content tag to display our buttons at the bottom. Now the way to know which ng-content is for which selector is, using a ‘<strong>select</strong>’ attribute. Syntax for this is, <em>select=“&lt;tag_name&gt;”</em>.</p><p>Check the code below how we can do this:</p><pre>&lt;form #form=”ngForm” (ngSubmit)=”onSubmit(form.value)”&gt;<br> <strong>&lt;ng-content select=”h3&quot;&gt;&lt;/ng-content&gt;</strong><br> &lt;div class=”form-group” style=”padding-top: 20px;”&gt;<br> &lt;label style=”font-weight: 500;” for=”alterEgo”&gt;Email Address:&lt;/label&gt;<br> &lt;input type=”text” class=”form-control” id=”alterEgo”&gt;<br> &lt;/div&gt;</pre><pre>&lt;div class=”form-group”&gt;<br> &lt;label style=”font-weight: 500;” for=”alterEgo”&gt;Password:&lt;/label&gt;<br> &lt;input type=”text” class=”form-control” id=”alterEgo”&gt;<br> &lt;/div&gt;</pre><pre><strong>&lt;ng-content select=”button”&gt;&lt;/ng-content&gt;</strong><br>&lt;/form&gt;</pre><p>And doing above changes our forms look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*AuBy8dtNOLBnMm8Qgc04kw.png" /></figure><p>This works similar to a document query selector. Instead of tag-name to select, we can also pass CSS class or id name like this: <em>select=“.class_name”</em> or <em>select=“#id_name”.</em></p><p><strong>Note: <em>&lt;ng-content&gt;</em> does not produce a content, it simply projects existing content.</strong></p><p>I hope you enjoyed this article. If you have any queries, you can ask me in the comments section below. Thank You !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819106f9e6e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Understanding of RxJS]]></title>
            <link>https://tanpure-anjali.medium.com/basic-understanding-of-rxjs-7406b56bf976?source=rss-ab91b1950965------2</link>
            <guid isPermaLink="false">https://medium.com/p/7406b56bf976</guid>
            <dc:creator><![CDATA[Anjali Tanpure]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 05:06:37 GMT</pubDate>
            <atom:updated>2020-12-16T05:50:45.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! In this article I will be talking about RxJS as I have just completed a course from Pluralsight on <a href="https://www.pluralsight.com/courses/rxjs-angular-reactive-development">RxJS in Angular: Reactive Development</a> by the author Deborah Kurata. Thanks to her as she has explained the terms very well. This post includes some of the learning from this course as well. Let’s get started!</p><p>RxJs is a library that brings the concept of “reactive programming” to the web. With <strong>R</strong>eactive E<strong>x</strong>tension of <strong>J</strong>ava<strong>S</strong>cript i.e. RxJS, we leverage patterns to collect data from multiple sources. Combine data for display, cache data to improve performance and react to the user.</p><p>Reactive extensions were originally developed by Microsoft as Rx.Net. Since that time, the reactive extension library has been implemented for several other languages including Java(RxJava), Python(RxPy), Ruby(Rx.rb), JavaScript(RxJS).</p><h3>What is RxJS ?</h3><p>According to<a href="https://rxjs.dev/"> rxjs.dev</a>,</p><blockquote>RxJS is a library for <a href="https://en.wikipedia.org/wiki/Reactive_programming">reactive programming</a> using Observables, to make it easier to compose asynchronous or callback-based code.</blockquote><h4>But what does it mean ?</h4><p>Imagine RxJS as, “Manage the incoming data as it flows through time” i.e. the <em>streams. </em><strong>stream</strong> is nothing but a sequence of data elements made available over time. It can be thought of as flow of data being processed one at a time rather than in chunks.</p><p>Imagine a stream as a conveyor belt let’s say in a bottle factory, each bottle being processed one at a time rather than in large batches.</p><figure><img alt="source: https://stock.adobe.com" src="https://cdn-images-1.medium.com/max/1024/1*E8GdREKVwjWbw2C2SPxJMQ.png" /><figcaption>Image source: <a href="https://stock.adobe.com/">https://stock.adobe.com</a></figcaption></figure><p>The data can be of any type such as numbers, strings, or an array of employees or messages or can be a response returned from an HTTP request. The stream can come from user input such as mouse or keyboard events. We can use RxJS, “to manage a stream of any data”.</p><h3>RxJS Terms</h3><h4>Observer / Subscriber:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCjhbbZRynEvjTSOP5XAeA.png" /></figure><p>Imagine an observer as an employee in a factory who is observing the bottle as they are emitted onto a conveyor belt. So as an observer, employee get notification as:</p><ul><li>The next bottle comes so that he can process it in whatever way he wants.<br><em>[</em> next item process it:<em> </em><strong><em>next()</em></strong><em> ]</em></li><li>If some bottle has a defect<em> [ </em>error occurred, handle it:<strong><em> error()</em></strong><em> ]</em></li><li>When all bottles has been completed <em>[ </em>complete, you’re done:<strong> <em>complete()</em></strong><em> ]</em></li></ul><p>So RxJS observer observes the stream, &amp; responds to it’s notification.<br>From Angular documentation observer is,</p><blockquote>A JavaScript object that defines the handlers for the notifications you receive.</blockquote><p>Basically in RxJS, observer is also defined as an interface with next(), error() and complete() methods. One such class that implements an observer interface is <strong>Subscriber</strong>. In RxJS, each observer converted into a subscriber. <br>A subscriber is an observer with additional features to unsubscribe from an observable.<br>Let’s see how observable looks like :</p><pre><em>const observer = {<br> next: bottle =&gt; console.log(`Bottle is emitted ${bottle}`);<br> error: err =&gt; console.log(`Error occurred: ${err}`);<br> complete: () =&gt; console.log(`No more bottles. Goodbye for the day!`);<br>};</em></pre><h4>Observable / Observable Stream</h4><p>Referring to the above images, our stream is a bottle moving along the conveyor. In RxJS, a stream of data is called an observable stream. Also called an ‘observable sequence’ or just an ‘observable’ or ‘stream’. Observables can emit finite/infinite numbers of values.</p><p>Observables can be:</p><ul><li>Synchronous — items are emitted to the stream immediately</li><li>Asynchronous — items are emitted at some future point in time</li></ul><p>We can create observables using the ‘new’ keyword.</p><pre><em>const bottleStream = new Observable (bottleObserver =&gt; {<br> bottleObserver.next(‘bottle 1’); <br> bottleObserver.next(‘bottle 2’);<br> bottleObserver.complete();<br>});</em></pre><p>Using the above example to understand the concepts. Normally we do not write code like this. There are easier ways to create observable streams.</p><p>Will the above code emit two bottle strings to our streams ? Well the answer is NO. Observables are lazy, and don’t execute when they are defined. So guys what’s missing here ? Yes, we have not started the stream. We start the stream by calling the subscribe() method of the observable.</p><p><strong>We must subscribe to the observable to start a stream otherwise, no values are emitted. </strong>Like this:</p><pre><em>const sub = bottleStream.subscribe(observer);</em></pre><p>When we subscribe we pass, in the observer to monitor that subscription &amp; react each time an item is emitted. subscribe() method returns a subscription, which represents the execution of the observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*8b6SdgEAk9lPau53g3z12Q.png" /></figure><p>Let’s see how it’s executed ?</p><ol><li>As we have subscribed to the observable, code in the constructor gets executed.</li><li>It first calls next() on the observer, displaying the next method message in the console.</li><li>It calls next() again, displaying a second message in the console.</li><li>Lastly it calls the complete() method, stopping our stream and displaying our complete message.</li></ol><p>When working with observables we don’t normally create an observer like above, and pass it into the subscribe method. Rather we pass the next, error and complete methods, directly into the subscribe method like this:</p><pre><em>const sub = bottleStream.subscribe({<br> next: bottle =&gt; console.log(`Bottle is emitted ${bottle}`);<br> error: err =&gt; console.log(`Error occurred: ${err}`);<br> complete: () =&gt; console.log(`No more bottles. Goodbye for the day!`);<br>});</em></pre><p>Each of the arguments to the observer i.e. next, error, complete are optional, only specify what is needed.</p><h4>Stop the stream:</h4><p>Now, in a bottle factory at the end of day, what happens if users do not stop the conveyor belt ? Well bottles get spread everywhere in factories. Similarly if we do not stop the RxJS stream, (like we stopped above using complete method) it will create memory leak issues. There are multiple ways to stop the stream:</p><ul><li>Call observer’s complete() method.</li><li>Use completing operators like : of(), from().</li><li>If an observer throws an error, the stream will stop automatically.</li><li>By unsubscribing the subscription using unsubscribe method: <em>sub.unsubscribe();</em></li></ul><h4>Creating observables:</h4><p>In Angular we often work with observables, which Angular creates for us. But sometimes we want to create one ourselves. We can create observables by using an observable constructor using the new keyword that we have seen above. But RxJS provides simple functions for us to create observables they are:</p><ul><li>of(): Creates an observable using a set of defined values.<br><em>const bottleStream = of(‘bottle1’, ‘bottle2’);</em></li><li>from(): creates an observable from an array/other data structure.<br><em>const bottleStream = from([‘bottle1’, ‘bottle2’]);</em></li><li>fromEvent(): Creates an observable with any DOM event.<br>const source = fromEvent(document, ‘click’);</li></ul><p>These commonly used creation functions are static and we can call them without object. There are some more creation functions available in RxJS.</p><p>I hope you have understood the important terms of RxJS. Now moving forward to the RxJS operators.</p><h3>Operators</h3><p>Operators are nothing but functions. In RxJS, we pipe each emitted item through a set of operators. The operators can transform, filter, or process the item. We also use operators to compose streams. We can apply multiple operators in sequence using the observable pipe method.</p><p>Take a look at the example below! There is an observable stream of three numbers including 3, 2 and 4 which is our source observable.</p><pre>of(3, 2, 4).pipe(<br> map(val =&gt; val * 2),<br> tap(val =&gt; console.log(val)),<br> take(2)<br>).subscribe(console.log);</pre><h4>pipe():</h4><p>We have called the pipe() method of the observable and pass different RxJS operators like map, tap and take to it separated by commas. Now when we subscribe to the source observable, the source observable stream starts emitting the items. Each operator pipes through the series of operators in <strong>sequence.</strong></p><p>Here first 3 will be emitted and processed through each operator, then 2 and then 4. The value output by the last operator is the value emitted to the result observable and processed by the observable’s next() method which we pass to the subscribe.</p><p>When we subscribe to an observable with operators, each operator takes an observable as an input, the operator subscribes to that input observable and creates, processes and returns an output observable. Now that output observable will be the input observable for the next operator in sequence. We can think theses operators as a pipeline.</p><p>Let’s move on to the operators that we have used in our pipe to solve this example.</p><h4>map():</h4><p>This is the most commonly used operator in RxJS. map transforms or changes each emitted item as defined by a function we provide, hence it is called as a transformation operator. Here in our example, we map/transforms each emitted item to two times it’s value. For each item in the source, exactly one mapped item is emitted.</p><p><strong>Used for: </strong>Making changes to each item in the source stream.</p><h4>tap():</h4><p>The purpose of the tap operator is to perform an operation that does not affect the stream. Formally, tap is a utility operator. If we aren’t getting the results that we expect, then we can use a tap operator to debug the issue. For tap, input observable is the same as output observable.</p><p><strong>Used for:</strong></p><ol><li>Debugging</li><li>Performing actions outside the flow of data that don’t modify the stream.</li></ol><h4>take():</h4><p>The take operator emits specified number of items. It is a filtering operator. When an item is emitted, take counts the item. If the count ≤ specified number, it emits the output stream. When it equals to the specified number, it completes the stream.</p><p><strong>Used for:</strong></p><ol><li>Taking a specified numbers of items.</li><li>Limiting unlimited streams such as streams created by an ‘interval’ function.</li></ol><p>I hope you understand these operators, Now, let’s execute our example. <br>Our source observable stream contains 3 numbers: 3, 2 and 4 respectively.</p><ol><li><em>map</em>: First 3 will be emitted and pass it to map function: 3 * 2 = 6.</li><li><em>tap</em>: The first tap logs it to the console. // 6</li><li><em>take</em>: will taken it as first time</li><li><em>subscribe</em>: logs 6 to the console. // 6</li><li><em>map</em>: Secondly 2 will be emitted, so 2 * 2 = 4.</li><li><em>tap</em>: The second tap logs it to the console. // 4</li><li><em>take</em>: will taken it as second time</li><li><em>subscribe</em>: logs 4 to the console. // 4</li></ol><p>As we have provided ‘ 2’ as an argument to take. So it will emit at most two values and stream will be stopped and no 3rd value will be emitted i.e. 4.</p><p>So final output of our example will be:</p><pre>of(3, 2, 4).pipe(<br> map(val =&gt; val * 2),<br> tap(val =&gt; console.log(val)),<br> take(2)<br>).subscribe(console.log);</pre><pre>Output:<br>6<br>6<br>4<br>4</pre><p>There are about 100+ built-in RxJS operators. It takes time to learn what they all do and how they can be used. Now let’s see how to handle errors with observables.</p><h3>Error Handling</h3><p>While working with observables it’s important to catch the errors. If there is an error, any stream will be stopped and no more values can emit. There are two strategies to handle the errors with observables. In both strategies, the first step is to catch the error that brings us to the next() operator.</p><ol><li>Catch and Replace</li><li>Catch and Rethrow</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_pu7Ejv9djEb5dGI7Tjaw.png" /></figure><h4>Catch and Replace:</h4><p>It involves catching the error &amp; replacing errored observable with a new observable. Replacement of errored observable depends on the error and observable. We could return hard-coded data or locally stored data or empty array/value as a replaced observable when error comes using catchError().</p><p><strong>catchError():<br></strong>Catches an error that occurred on observable<em>.</em> Here we catch the error &amp; pass in a handleError method for processing the error.<em><br>catchError(this.handleError);</em></p><p>catchError is useful to rethrow the error or replacing the errored observable so that we can continue the stream even after error occurs.</p><pre>const http$ = this.http.get&lt;Bottle[]&gt;(‘/api/bottlesDetail’);<br>http$<br> .pipe(<br>   catchError(err =&gt; of([{id: 1, material: &#39;glass&#39;, color: &#39;red&#39;}])<br> .subscribe(<br>   res =&gt; console.log(‘HTTP response’, res),<br>   err =&gt; console.log(‘HTTP Error’, err),<br>   () =&gt; console.log(‘HTTP request completed.’)<br> );</pre><p>When the error occurs, catchError operator is going to take error, unsubscribes from the input stream<em> </em>and return an observable which is an array of a bottle object, using of operator. The observer does not get notified of the error as catchError already handled the error. Instead observable’s next method will call with the new observable from catchError operator.</p><h4>Catch and Rethrow:</h4><p>In this mechanism, we rethrow the error caught by the catchError using ‘throwError’. throwError creates an observable that never emits any value. Instead, it errors out immediately using the error caught by catchError.</p><pre>const http$this.http.get&lt;Bottle[]&gt;(&#39;/api/bottlesDetail&#39;);</pre><pre>http$<br>    .pipe(<br>        map(res =&gt; res[&#39;payload&#39;]),<br>        catchError(err =&gt; {<br>            console.log(&#39;caught mapping error and rethrowing&#39;, err);<br>            return throwError(err);<br>        })<br>    )</pre><p>Here, we rethrow an error from catchError. This is how we can handle errors in RxJs.</p><p>I hope that you have enjoyed this post on RxJS terms, operators and how to handle errors. Also, if you have some questions or comments please let me know in the comments. Thank you!</p><h3>References:</h3><ul><li><a href="https://rxjs.dev/">https://rxjs.dev/</a></li><li><a href="https://www.pluralsight.com/courses/rxjs-angular-reactive-development">RxJS in Angular: Reactive Development</a></li><li><a href="https://en.wikipedia.org/wiki/Reactive_extensions">https://en.wikipedia.org/wiki/Reactive_extensions</a></li><li><a href="https://www.udemy.com/course/rxjs-course/">https://www.udemy.com/course/rxjs-course/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7406b56bf976" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>