<?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 Ravithamara on Medium]]></title>
        <description><![CDATA[Stories by Ravithamara on Medium]]></description>
        <link>https://medium.com/@rwijayabandu?source=rss-8e2e1831b91c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Nv7zWSUEXhRLcB7M</url>
            <title>Stories by Ravithamara on Medium</title>
            <link>https://medium.com/@rwijayabandu?source=rss-8e2e1831b91c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:04:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rwijayabandu/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[Java vs JavaScript: enhanced for loop and forEach() explained]]></title>
            <link>https://medium.com/@rwijayabandu/java-vs-javascript-enhanced-for-loop-and-foreach-explained-8fc05dfa3d60?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc05dfa3d60</guid>
            <category><![CDATA[enhanced-for-loop]]></category>
            <category><![CDATA[javascript-foreach]]></category>
            <category><![CDATA[foreach-loop]]></category>
            <category><![CDATA[for-of-loop]]></category>
            <category><![CDATA[for-each-loop-in-java]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 18:02:14 GMT</pubDate>
            <atom:updated>2026-01-10T18:02:14.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java for-each / enhanced for loop</h3><blockquote><strong>syntax</strong></blockquote><pre>for(dataType variable : collection){<br><br>}</pre><ul><li>Used to iterate over arrays and collections.</li><li>Simple and more readable than traditional loop.</li><li>No need to use index of elements.</li><li>Provide only values not indexes</li><li>Always iterating over all elements from first to last.</li><li>Can use break or continue</li></ul><blockquote><strong>Limitations</strong></blockquote><ul><li>Cannot iterate in reverse order</li><li>Cannot directly access the index of element</li><li>Cannot modify elements directly</li></ul><p><strong>example with array</strong></p><pre>int numbers[] = {1,2,3,4};<br><br>for(int num: numbers){<br>  System.out.println(num);<br>}</pre><p><strong>example with collection</strong></p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Dog&quot;, &quot;Cat&quot;,&quot;Elephant&quot;);<br><br>for(String name: names){<br>  System.out.println(name);<br>}</pre><h3>Java forEach() method</h3><ul><li>Not a loop; Method provided by Iterable interface</li><li>Cannot use break or continue</li><li>Can modify elements</li></ul><pre>List&lt;String&gt; names = Arrays.asList(&quot;Dog&quot;, &quot;Cat&quot;,&quot;Elephant&quot;);<br>names.forEach(System.out::println); // used method reference<br><br>List&lt;String&gt; names = Arrays.asList(&quot;Dog&quot;, &quot;Cat&quot;,&quot;Elephant&quot;);<br>names.forEach(name -&gt; System.out.println(name)); // used lambda function</pre><h3>JavaScript for-each / for ….of / enhanced for loop</h3><blockquote><strong>syntax</strong></blockquote><pre>for( const variable of array){<br><br>}</pre><ul><li>Used to iterate over arrays, strings, maps, sets</li><li>Simple and more readable than traditional loop.</li><li>Provide only values not indexes</li><li>Can use break or continue</li></ul><blockquote><strong>Limitations</strong></blockquote><ul><li>Cannot iterate in reverse order</li><li>Cannot directly access the index of element</li></ul><p><strong>example with array</strong></p><pre>const numbers = [1,2,3,4];<br><br>for(const num of numbers){<br>  console.log(num);<br>}<br><br>const names = [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Elephant&quot;];<br><br>for(const name of names){<br>  console.log(name);<br>}</pre><h3>JavaScript forEach() method</h3><ul><li>Cannot use break or continue or return</li><li>Can access index</li><li>Can modify elements</li></ul><pre>const names = [&quot;Dog&quot;, &quot;Cat&quot;, &quot;Elephant&quot;];<br>names.forEach(name =&gt; console.log(name));</pre><h3>JavaScript for ….in loop</h3><blockquote><strong>syntax</strong></blockquote><pre>for(const key in object){<br><br>}</pre><ul><li>Used to iterate over enumerable keys</li><li>Provide only keys not values</li><li>Best for objects, not recommended for arrays</li><li>Can use break or continue</li></ul><pre>const person = {<br>    name: &quot;Harry&quot;,<br>    age: 59<br>};<br><br>for (const key in person) {<br>    console.log(key + &quot; &gt; &quot; + person[key]);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc05dfa3d60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular in Depth: Top 30 Interview Questions Concepts Explained Simply]]></title>
            <link>https://medium.com/@rwijayabandu/angular-in-depth-top-30-interview-questions-concepts-explained-simply-a5c50e0f7aa9?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c50e0f7aa9</guid>
            <category><![CDATA[angular-19]]></category>
            <category><![CDATA[angular-interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[angular-concepts]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 13:20:59 GMT</pubDate>
            <atom:updated>2025-12-25T13:20:59.628Z</atom:updated>
            <content:encoded><![CDATA[<p>1️⃣ <strong>What is Angular CLI</strong></p><p>It is a developer tool used to create, build, test Angular applications</p><pre>ng new project-name<br>ng serve<br>ng generate component test-component<br>ng build<br>ng test</pre><p>2️⃣<strong>Your Angular version and features introduced</strong></p><ul><li>Angular 19</li><li>Newly generated components, pipes &amp; directives are by default standalone, no need to explicitly set standalone: true</li><li>Signal API stabilized including input(), output(), model(), viewChild()</li><li>Improved server side rendering</li><li>Hot Module Replacement — changes to styles and templates can trigger HMR without full page refresh</li></ul><p>3️⃣ <strong>Standalone components vs Module based components</strong></p><blockquote>Standalone Components</blockquote><ul><li>Self contained components which don’t require @ngModule for configuration</li><li>Dependencies are declared directly in imports array within the component itself</li><li>Reduced boilerplate code and easier to load independently</li><li>Recommended for modern architecture</li><li>Faster initial load times</li></ul><blockquote>Non-Standalone Components (Module Based Components)</blockquote><ul><li>Must be declared in the @ngModule to use</li><li>Dependencies are managed in the @ngModule imports and declarations array</li><li>More boilerplate code due to @ngModule configuration</li><li>Still support for legacy &amp; large enterprise applications</li></ul><p>4️⃣ <strong>Passing data to sibling components</strong></p><ul><li>Use shared service with BehaviorSubject</li><li>Use shared service with Signal</li><li>Use parent component as the mediator (since both have same parent pass data up from one sibling to parent and then pass it down to another sibling)</li><li>Use global NgRx store for large applications (one sibling dispatches an action, store updates state and other sibling select the updated state from store)</li></ul><p>5️⃣ <strong>Passing data between parent and child</strong></p><ul><li>Use shared service with BehaviorSubject</li><li>Use shared service with Signal</li><li>Use @Input decorator to pass data from parent to child and use @Output decorator with EventEmitter to pass data from child to parent</li></ul><p>6️⃣ <strong>Reactive forms vs Template driven forms</strong></p><blockquote>Reactive forms</blockquote><ul><li>Form is model driven &amp; created in TypeScript</li><li>Use FormControl, FormGroup classes</li><li>Best for scalable, large, complex forms</li><li>Needs to import ReactiveFormsModule</li><li>Provides synchronous access to form values</li></ul><blockquote>Template-Driven forms</blockquote><ul><li>Form is defined in the HTML template</li><li>Use ngModel, ngForm, ngModelGroup directives</li><li>Best for simple, less scalable, small forms (login form, sign up form, contact form)</li><li>Needs to import FormsModule</li><li>Provides asynchronous access to form values</li></ul><p>7️⃣ <strong>Benefit of subject</strong></p><p>Subjects act as both observer and observable<br>They allow us to emit new values to observables using next() method</p><blockquote>Types of Subjects</blockquote><ul><li>subject — no initial value or replay available</li><li>behaviouralSubject — requires an initial value and emits values immediately to new subscribers</li><li>asyncSubject — emits latest values to subscribers on completion of async task (emits value only when the Observable completes)</li><li>replaySubject — replay specified number of last values to new subscribers</li></ul><p>8️⃣<strong>What are RxJS operators in Angular</strong></p><ul><li>RxJS(Reactive Extensions for JavaScript)</li><li>It is a library used for handling asynchronous and event-based programming using Observables</li><li>Operators are pure functions that take an Observable as input and return a new Observable<br>eg: of, from, fromEvent, take, takeUntil, catchError</li></ul><p>9️⃣ <strong>Debounce vs Throttle in RxJS</strong></p><p>They are rate limiting operators.</p><blockquote>debounceTime()</blockquote><ul><li>Waits for the user to stop emitting events. It emits only after silent period. <br>If new events keep getting the timer keeps resetting. Only the last event emits after the delay<br>Usages - autocomplete, avoid unnecessary API calls, search input boxes wait until user stops typing</li></ul><blockquote>throttleTime()</blockquote><ul><li>Emits the first event and ignore others for specific time.<br>It emits immediately, then wait for cooldown time and ignore other events during wait<br>Usages - prevent double click, scroll events, resize events, drag events, prevent spam clicks</li></ul><p>1️⃣0️⃣ <strong>Avoid multiple fetch calls with RxJS</strong></p><ul><li>Most common way to use shareReplay(1) — httpClient call will execute only once and reuse the last cached value. Multiple subscriptions reuse same response without repeating API calls</li><li>Use switchMap() to cancel previous API calls. Only the latest API call occurs</li><li>Use take(1) to ensure API call runs only once</li><li>Use throttleTime() to immediately execute first API call, then ignore others for a specific time</li><li>Use exhaustMap() to avoid repeated clicks, double clicks to prevent multiple API calls</li></ul><p>1️⃣1️⃣ <strong>Content projection</strong></p><ul><li>Pass content from parent component to a child component</li><li>Allows components to display content (external content) provided by outside the component</li><li>Use &lt;ng-content&gt; directive inside child component template</li><li>&lt;ng-content&gt; is similar to &lt;slot&gt; native HTML element</li></ul><p>1️⃣2️⃣ <strong>Guards in Angular</strong></p><p>Guards are used to control navigation and access to routes</p><ul><li>canActivate- control whether a user can enter a route</li><li>canDeactivate- control whether a user can leave a route</li><li>canActivateChild- control whether a user can enter a child route</li><li>Resolve- fetch data before route loads</li></ul><p>1️⃣3️⃣ <strong>When to use ng-template</strong></p><ul><li>Directive which allows to define a template for rendering dynamic content.</li><li>Commonly used for conditionally rendering parts of the DOM, reuse dynamic content, content projection using templates, Tooltip/Popover, lazy loaded content</li><li>It is not rendered in the DOM by default. But acts as a placeholder for a template that can be rendered using *ngIf, *ngFor</li></ul><p>1️⃣4️⃣ <strong>Pure pipes vs Impure pipes</strong></p><p>functions that accept an input and return a transformed value. There are built in pipes and custom pipes. All Angular pipes are default pure pipes. We typically use pipes to format data for display, keep templates clean, reuse transformation logic etc.</p><blockquote>Pure pipes</blockquote><ul><li>Runs only when its input reference changes</li><li>Executes when detects primitive value (String, Number, Boolean) changes or object and array reference changes</li><li>Ignores changes to internal properties of object or array</li><li>Recommended for most cases, high performance</li></ul><blockquote>Impure pipes</blockquote><ul><li>Runs on every change detection cycle regardless of input changes</li><li>Checks changes inside objects, arrays</li><li>Low performance</li><li>Not default in Angular pipes, must be explicitly marked pure: false</li></ul><p>1️⃣5️⃣ <strong>Ways of binding data in Angular</strong></p><blockquote>Interpolation {{ }}</blockquote><ul><li>used to display data from component to view</li></ul><pre>// component<br>export class Component{<br>  name = &#39;Ravi&#39;<br>}<br><br>// template<br>&lt;p&gt;{{name}}&lt;/p&gt;</pre><blockquote>Property binding [property]</blockquote><ul><li>one way binding which binds a DOM property to component property eg: [disabled], [href]</li></ul><pre>// component<br>imgUrl = &#39;logo.png&#39;<br><br>// template<br>&lt;img [src]=&quot;imgUrl&quot;&gt;</pre><blockquote>Event binding (event)</blockquote><ul><li>one way binding which binds user interaction (DOM events) to component eg: (click), (submit), (hover)</li><li>$event can be used to access data emitted by the event</li></ul><pre>// component<br>onClick() {<br>  console.log(&quot;&quot;)<br>}<br><br>// template<br>&lt;button (click)=&quot;onClick()&quot;&gt; Click Me &lt;/button&gt;</pre><blockquote>Two way binding [(ngModel)]</blockquote><ul><li>two way binding which keeps data in sync with component and template</li><li>enables seamless automatic synchronization where data flows from component to view and view to component</li></ul><pre>&lt;input [(ngModel)]=&quot;name&quot;&gt;<br>&lt;p&gt;{{ name }}&lt;/p&gt;</pre><p>1️⃣6️⃣ <strong>ngOnChanges life cycle hook</strong></p><p>method that is invoked immediately when input of a component changes. It is called before ngOnInit() for the first time and every subsequent changes after ngOnInit(). It triggers whenever the value of data bound property of a component changes.</p><p>1️⃣7️⃣ <strong>Ways to increase performance</strong></p><ul><li>Use lazy loaded components (load component only when user navigates to the route). This reduces initial load time and bundle size.</li><li>Ahead of Time (AOT) compiles HTML templates and components into optimized JS code during build. ng build — configuration production</li><li>Use Server Side Rendering (SSR). This reduces initial load time and SEO</li><li>Use async pipe to subscribe Observables or Promises (no need manual unsubscribe in ngOnDestroy).</li><li>Optimize RxJS usages.</li><li>Always unsubscribe from Observables which manually subscribes with .subscribe() in ngOnDestroy.</li><li>Use <em>debounceTime()</em> , <em>throttleTime()</em> operators to avoid unnecessary API calls when searching</li><li>Use OnPush to limit detecting changes changeDetection: ChangeDetectionStrategy.OnPush</li></ul><p>1️⃣8️⃣ <strong>Angular compilation types</strong></p><p>compile TypeScript and HTML templates into JavaScript code which browser can run.</p><blockquote>AOT (Ahead Of Time) Compilation</blockquote><ul><li>Happens during build phase before browser run</li><li>Compiles TypeScript and HTML templates into executable JS code ahead of time which helps faster loading and better performance</li><li>Faster initial loading since the compilation has already been done and the browser only loads precompiled code.</li><li>Smaller bundle size, faster performance in production but longer build times</li><li>Recommend in production, Angular CLI sets AOT by default in production</li><li>ng build — prod use AOT by default</li></ul><blockquote>JIT (Just In Time) Compilation</blockquote><ul><li>Happens in runtime on browser after build phase</li><li>Compiles application in browser as it loads</li><li>Slower performance in production, slower initial loading, larger bundle size</li><li>Recommend in development, since it allows rapid changes without need of rebuild</li><li>ng serve use JIT by default</li></ul><p>1️⃣9️⃣ <strong>Lazy loading in Angular</strong></p><p>Way to improve performance by loading components or modules only when they needed. That means only load them when user navigates to the route. It reduces initial load time.</p><pre>// module<br>{<br> path: &#39;feature&#39;, loadChildren: () =&gt; import(&#39;./feature/feature.module&#39;).then(m =&gt; m.FeatureModule)<br> }<br><br>// component<br>{<br> path: &#39;feature&#39;, loadComponent: () =&gt; import(&#39;./feature/feature.component&#39;).then((c) =&gt; c.FeatureComponent)<br>}</pre><p>2️⃣0️⃣ <strong>Eager loading in Angular</strong></p><p>Modules, components are loaded initially in application start up even if they are not needed immediately. It is the default behaviour of Angular if you didn&#39;t explicitly configure lazy loading</p><p>2️⃣1️⃣ <strong>Angular Universal</strong></p><p>Allows server side rendering for Angular applications which reduces initial load time, improving performance</p><p>2️⃣2️⃣ <strong>OnPush change detection</strong></p><p>By default Angular checks component data changes and updates DOM on every async event. But it can affect performance in large apps. When we use OnPush Angular only checks component data changes when an @Input reference changes, an event occurs from component, an Observable emits a value. It improves performance by reducing unnecessary checks</p><p>2️⃣3️⃣ <strong>Angular interceptors</strong></p><p>Modify HTTP requests and responses and allow to perform actions including add authentication tokens, loading spinners, handle errors globally, modify request URL or header</p><p>2️⃣4️⃣ <strong>Data types</strong></p><blockquote>Primitive data types (immutable)</blockquote><ul><li>number</li><li>string</li><li>boolean</li><li>null</li><li>undefined</li><li>symbol</li><li>bigint</li></ul><blockquote>Object types (mutable / Arrays and Functions are Objects in JavaScript)</blockquote><ul><li>Object</li><li>Array</li><li>Tuple</li><li>Enum</li><li>Function</li><li>Class</li><li>Interface</li></ul><blockquote>TypeScript only types (exist only in compile time not runtime / don’t belong to primitive or objects</blockquote><ul><li>any</li><li>unknown</li><li>never</li><li>void</li></ul><p>2️⃣5️⃣ <strong>Use of NgModule</strong></p><p>@NgModule is decorator used to define Angular module. Module is container to organize grouping related Angular components, directives, pipes, services and help dependency management via imports, exports</p><blockquote>properties of NgModule</blockquote><ul><li>declarations — declare the components, directives, pipes that belong to the NgModule.</li><li>providers-provide services to inject</li><li>imports-import other components, directives, pipes that this module depends on</li><li>exports-export declared components, directives, pipes to be available for other components and modules to import</li></ul><pre>@NgModule({<br> declarations: [],<br> imports: [],<br> exports: [],<br> providers: [],<br> bootstrap: []<br>})</pre><p>2️⃣6️⃣ <strong>What is a directive</strong></p><p>It allows to dynamically add custom behaviors to elements in DOM.</p><ul><li>Component Directive — just an Angular component. In Angular, components are type of directive.</li><li>Structural Directive —modify DOM by adding or removing elements *ngIf, *ngFor, *ngSwitch</li><li>Attribute Directive — modify appearance of DOM elements [ngClass], [ngStyle], [ngModel]</li></ul><p>2️⃣7️⃣ <strong>&lt;ng-container&gt;</strong></p><p>It is a grouping element and structural directive wrapper that allows you to apply directives like *ngIf, *ngFor without adding a DOM element. It acts as a placeholder. It makes cleaner HTML structure since no unnecessary DOM element eg: &lt;div&gt;, &lt;span&gt;</p><pre>&lt;div *ngFor=&quot;let item of items&quot;&gt;     // add extra DOM element<br>  &lt;p&gt;{{ item.name }}&lt;/p&gt;<br>&lt;/div&gt;;<br><br><br>&lt;ng-container *ngFor=&quot;let item of items&quot;&gt;<br>  &lt;p&gt;{{ item.name }}&lt;/p&gt;<br>&lt;/ng-container&gt;</pre><p>2️⃣8️⃣ <strong>Advantages over React.js</strong></p><ul><li>Angular is a framework which provides everything you need out of the box including routing, HTTP client, forms management, state management while React is a library which you may need to import third party libraries</li><li>Angular provides two way data binding ability while React typically use one way data binding</li><li>Angular has built in dependency injection while React doesn’t have built in dependency injection</li><li>Angular uses TypeScript by default which provides static typing while React uses JavaScript which provides dynamic typing (React also support TypeScript)</li><li>Angular has directives and pipes while React doesn’t have equivalent tool</li><li>Angular has built in RxJS support which asynchronous events, streams make easier while React can use RxJS too but it is not built in. React typically use useEffect or Redux for async logic</li></ul><p>2️⃣9️⃣ <strong>Why client side frameworks introduced</strong></p><p>They were introduced to handle complex dynamic web applications. Before, web apps sent requests to the server for each user interaction and full page reload (MPA) which led to slower poor user experience. Earlier navigation between pages caused a full page reload. But CSF allowed to update parts of web pages without reloading. CSF enabled SPA where application loaded once and only parts of the page were updated. Earlier they used server rendered architecture where HTML + logic tightly coupled and there was no separation of logic. But with CSF logic became separated with component based architecture and reusable modular components made development easier. CSF made web applications faster, scalable, enhanced user experience, client side routing (SPA), state management, more interactive and improved performance</p><p>3️⃣0️⃣ <strong>What are SPA</strong></p><p>SPA loads single HTML page and dynamically updates content without full page reload. ALL SPA rely on CSR and with SPA interactions are faster, client side routing enabled, supports caching for offline access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c50e0f7aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios vs HttpClient: A Complete Guide to Making API Requests]]></title>
            <link>https://medium.com/@rwijayabandu/axios-vs-httpclient-a-complete-guide-to-making-api-requests-d60105fb9693?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60105fb9693</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[axios-interceptor]]></category>
            <category><![CDATA[angular-httpclient]]></category>
            <category><![CDATA[axios-vs-fetch]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 18:20:51 GMT</pubDate>
            <atom:updated>2025-11-04T18:20:51.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>1️⃣ Axios</h3><p>Axios is modern, open-source, promise-based HTTP client used in React applications for making API requests, which is an alternative to the native JavaScript fetch API. It enhances the process of sending asynchronous HTTP requests.</p><p>Axios is installed using npm or yarn.<br> <strong>npm install axios </strong>or <strong>yarn add axios</strong></p><p>After installed, it is imported into React component<br><strong> import axios from &#39;axios&#39;;</strong></p><p>Axios returns promises, just like the JavaScript fetch API allowing the use of .then() for successful responses and .catch() for error handling. It can also be used with modern <strong>async/await</strong>.</p><p><strong>Basic Syntax</strong></p><p>axios.get(&quot;https://somewebsite.com/users&quot;);</p><p>In a basic request, you pass the URL as the first argument. You can also include second optional parameter for additional settings like headers and request body.</p><p><strong>Handling Response</strong></p><pre>axios.get(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; console.log(response.data)); // Parsed JSON data</pre><p>The response object <strong>automatically parses JSON</strong> data. Therefore no manual parsing is required like we do in fetch method. (response.json() with fetch)</p><p><a href="https://medium.com/@rwijayabandu/everything-you-need-to-know-about-javascripts-fetch-api-29a66822b950">With fetch method, we need to manually parse JSON like this</a></p><pre>fetch(&quot;https://somewebsite.com/users&quot;)<br> .then(response =&gt; response.json()) // Manual JSON parsing<br> .then(data =&gt; console.log(data));</pre><p><strong>Error Handling</strong></p><pre>axios.get(&quot;https://somewebsite.com/users&quot;)<br>  .then(response =&gt; console.log(response.data))<br>  .catch(error =&gt; console.error(error));</pre><p>It automatically throws an error for <strong>non-2xx status </strong>codes, so it will catch in .catch() So no need to manually check <strong>(!response.ok) </strong>like in fetch method.</p><p><strong>Interceptors </strong>-&gt; Axios provides request and response interceptors, which are functions that Axios calls before requests are sent or responses are received. These are useful for</p><ul><li>Adding authentication tokens to request headers.</li><li>Handle global error(eg: redirecting on 401 Unauthorized errors).</li><li>Logging requests and responses.</li></ul><p><strong>Custom Hooks</strong> -&gt; Axios can be integrated with React Hooks to create reusable data-fetching logic, encapsulating API calls and state management within custom hooks like <strong>useAxios </strong>or <strong>useFetchData</strong>.</p><p><strong>Cancel Request</strong> -&gt; It allows you to abort ongoing requests, which is useful in rapid user interaction (eg: typing in a search box where you might want to cancel previous requests that are no longer needed).</p><h4>Sample requests with Axios with .then()</h4><p>1️⃣<strong>GET</strong></p><pre>axios.get(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><p>2️⃣<strong>POST</strong></p><pre>axios.post(&quot;https://somewebsite.com/add&quot;, {<br>    // data you want to send<br>})<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><p>It automatically serializes the object you provide into JSON. So no need to use <strong>JSON.stringify</strong> like in the native <a href="https://medium.com/@rwijayabandu/everything-you-need-to-know-about-javascripts-fetch-api-29a66822b950">fetch </a>method.</p><pre>axios.post(&quot;https://somewebsite.com/add&quot;,{<br>    name: &quot;John Doe&quot;,<br>    age: 30<br>});</pre><p>It automatically handles the <strong>Content-Type: application/json</strong> when you send a JavaScript object. So no need to manually set the <strong>headers </strong>like in the fetch method.</p><p>But if you anyway want to explicitly set headers due to specific reason ⬇️</p><pre>axios.post(&quot;https://somewebsite.com/add&quot;, {<br>    // data you want to send<br>}, {<br>    headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br>})<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><blockquote>You can add multiple header fields if needed. It is common to customize headers when working with APIs that require authentication or need to receive specific content types</blockquote><pre>axios.post(&#39;https://somewebsite.com/add&#39;, {<br>  // data you want to send<br>}, {<br>  headers: {<br>    &#39;Authorization&#39;: &#39;Bearer ACCESS_TOKEN&#39;,<br>    &#39;Accept&#39;: &#39;application/json&#39;,<br>  }<br>})<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><p>3️⃣<strong>PUT</strong></p><pre>axios.put(&quot;https://somewebsite.com/update/1&quot;, {<br>    // data you want to send<br>})<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><p>4️⃣<strong>DELETE</strong></p><pre>axios.delete(&quot;https://somewebsite.com/delete/1&quot;)<br>.then(response =&gt; console.log(response.data))<br>.catch(error =&gt; console.error(error));</pre><p>We can use <strong>async/await </strong>for more readable code instead of .then() chaining. It allows asynchronous code to behave like synchronous. <strong>await</strong> pauses method until the promise resolves. It is better to use <strong>async/await</strong> over <strong>.then()/.catch()</strong> since it makes easy to use conditionals <strong>try/catch </strong>is simpler than chained <strong>.catch()</strong></p><h4>Sample requests with Axios (with async/await)</h4><p>1️⃣<strong>GET</strong></p><pre>async function getUsers() {<br>  try {<br>    const response = await axios.get(&quot;https://somewebsite.com/users&quot;);<br>    console.log(response.data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>2️⃣<strong>POST</strong></p><pre>async function addUser(userData) {<br>  try {<br>    const response = await axios.post(&quot;https://somewebsite.com/add&quot;, userData);<br>    console.log(response.data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>3️⃣<strong>PUT</strong></p><pre>async function updateUser(id, updatedData) {<br>  try {<br>    const response = await axios.put(`https://somewebsite.com/update/${id}`, updatedData);<br>    console.log(response.data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>4️⃣<strong>DELETE</strong></p><pre>async function deleteUser(id) {<br>  try {<br>    const response = await axios.delete(`https://somewebsite.com/delete/${id}`);<br>    console.log(response.data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p><strong>Advantages over JavaScript fetch API</strong></p><ul><li>Automatic JSON parsing: No need for <strong>response.json() , </strong>No need for<strong> </strong><strong>JSON.stringify</strong></li><li>Built-in error handling: Simpler error management.</li><li>Interceptors: Powerful feature for global request/response modification.</li><li>Cancellation of requests: Ability to cancel pending requests.</li><li>Supports All HTTP Methods<strong>:</strong> Including GET, POST, PUT, DELETE, PATCH etc.</li><li>Built in support for cross-site request forgery (CSRF)</li></ul><h3>2️⃣ Http Client</h3><p>HTTP Client is a modern, built-in, promise-like service used in Angular applications for making HTTP requests to APIs. It is part of the <strong>@angular/common/http</strong> package and provides a powerful and type-safe way to interact with RESTful services. It is fully integrated into Angular’s ecosystem. It is an alternative to native fetch() or third-party libraries like Axios</p><p><strong>HTTP Client</strong> is built into Angular projects created using the Angular CLI. The <strong>HttpClientModule </strong>needs to be imported into root module.</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br><br>@NgModule({<br>  imports: [HttpClientModule],<br>})<br>export class AppModule {}</pre><p>After importing, inject the <strong>HttpClient</strong> service to your component or service.</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><p>HttpClient return <strong>RxJS Observables</strong>, not promises.</p><p><strong>Basic Syntax</strong></p><p>this.http.get(&#39;https://somewebsite.com/users&#39;);</p><p>In a basic request, you pass the URL as the first argument. You can also include second optional parameter for additional settings like headers and request body.</p><p><strong>Handling Response</strong></p><p>You subscribe to the returned Observable using .subscribe() to access data or handle errors.</p><pre>this.http.get(&#39;https://somewebsite.com/users&#39;)<br>  .subscribe(response =&gt; console.log(response), // Parsed JSON data<br>  );</pre><p>Angular’s HttpClient <strong>automatically parses JSON</strong>, so there’s no need for manual JSON.parse() like with the fetch() API.</p><p><strong>Error Handling</strong></p><p>Angular provides error handling using <strong>RxJS operators</strong> like catchError.</p><pre>import { catchError } from &#39;rxjs/operators&#39;;<br>import { throwError } from &#39;rxjs&#39;;<br><br>this.http.get(&#39;https://somewebsite.com/users&#39;)<br>  .pipe(<br>    catchError((error) =&gt; {<br>      console.error(error);<br>      return throwError(() =&gt; error);<br>    })<br>  )<br>  .subscribe({<br>    next: (data) =&gt; console.log(data),<br>    error: (error) =&gt; console.error(&#39;Handled in subscribe:&#39;, error)<br>  });</pre><p>HttpClient treats <strong>non-2xx responses </strong>as errors, automatically triggering the error callback.</p><h4>Sample requests with Http Client</h4><p><strong>1️⃣ GET</strong></p><pre>this.http.get(&#39;https://somewebsite.com/users&#39;)<br>  .subscribe({<br>    next: (data) =&gt; console.log(data),<br>    error: (error) =&gt; console.error(error)<br>  });</pre><p><strong>2️⃣ POST</strong></p><p>Automatically serializes JavaScript objects to JSON. So no need to use <strong>JSON.stringify</strong> like in the native <a href="https://medium.com/@rwijayabandu/everything-you-need-to-know-about-javascripts-fetch-api-29a66822b950">fetch </a>method.</p><pre>this.http.post(&#39;https://somewebsite.com/add&#39;, {<br>  name: &#39;John Doe&#39;,<br>  age: 30<br>}).subscribe({<br>  next: (data) =&gt; console.log(data),<br>  error: (error) =&gt; console.error(error)<br>});</pre><p>It automatically handles the <strong>Content-Type: application/json</strong>. So no need to manually set the <strong>headers </strong>like in the fetch method. However, you can still customize headers if needed ⬇️</p><pre>import { HttpHeaders } from &#39;@angular/common/http&#39;;<br><br>const headers = new HttpHeaders({<br>  &#39;Authorization&#39;: &#39;Bearer ACCESS_TOKEN&#39;,<br>  &#39;Content-Type&#39;: &#39;application/json&#39;<br>});<br><br>this.http.post(&#39;https://somewebsite.com/add&#39;, { <br>    // data you want to send<br>  }, { headers })<br>  .subscribe({<br>    next: (data) =&gt; console.log(data),<br>    error: (error) =&gt; console.error(error)<br>  });</pre><p><strong>3️⃣ PUT</strong></p><pre>this.http.put(&#39;https://somewebsite.com/update/1&#39;, { <br>    // data you want to send<br> }).subscribe({<br>    next: (data) =&gt; console.log(data),<br>    error: (error) =&gt; console.error(error)<br>  });</pre><p><strong>4️⃣ DELETE</strong></p><pre>this.http.delete(&#39;https://somewebsite.com/delete/1&#39;)<br>  .subscribe({<br>    next: (data) =&gt; console.log(data),<br>    error: (error) =&gt; console.error(error)<br>  });</pre><h4>Sample requests with Http Client with async/await firstValueFrom</h4><p>Since HttpClient returns Observables, you can convert them to Promises using <strong>RxJS helpers</strong> like firstValueFrom or lastValueFrom.</p><pre>import { firstValueFrom } from &#39;rxjs&#39;;<br><br>async getUsers() {<br>  try {<br>    const response = await firstValueFrom(http.get(&#39;https://somewebsite.com/users&#39;));<br>    console.log(response);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>We can create a custom service to avoid the repetition of API logic in components</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  private apiUrl = &#39;https://somewebsite.com&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  getUsers(): Observable&lt;any&gt; {<br>    return this.http.get&lt;any&gt;(`${this.apiUrl}/users`);<br>  }<br><br>  addUser(userData: any): Observable&lt;any&gt; {<br>    return this.http.post&lt;any&gt;(`${this.apiUrl}/add`, userData);<br>  }<br><br>  updateUser(id: number, updatedData: any): Observable&lt;any&gt; {<br>    return this.http.put&lt;any&gt;(`${this.apiUrl}/update/${id}`, updatedData);<br>  }<br><br>  deleteUser(id: number): Observable&lt;any&gt; {<br>    return this.http.delete&lt;any&gt;(`${this.apiUrl}/delete/${id}`);<br>  }<br>}</pre><p><strong>Advantages over JavaScript fetch API</strong></p><ul><li>Automatic JSON parsing: No need for <strong>response.json()</strong>, No need for <strong>JSON.stringify</strong></li><li>Type safety with TypeScript by enforcing type for request and response</li><li>Built in error handling with RxJS</li><li>Interceptors for request and response</li><li>Request cancellation by unsubscribing observables</li><li>Supports all HTTP methods including GET, POST, PUT, DELETE, PATCH etc</li><li>Automatic CSRF handling when backend sets the cookie</li><li>Integrated with Angular dependency injection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNsVUcw1YqnZbi-9B_-Nkg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60105fb9693" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About JavaScript’s fetch() API]]></title>
            <link>https://medium.com/@rwijayabandu/everything-you-need-to-know-about-javascripts-fetch-api-29a66822b950?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a66822b950</guid>
            <category><![CDATA[javascript-fetch-api]]></category>
            <category><![CDATA[async-await-javascript]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[json-response]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 14:19:19 GMT</pubDate>
            <atom:updated>2025-10-06T14:19:19.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLI5ogo1rGqn4jQSwMM1WA.png" /></figure><p>Fetch()is a modern, <strong>promise-based</strong> API used for making network requests. It was introduced in ES6 and provides a native and flexible way to perform <strong>HTTP</strong> requests asynchronously. It is a cleaner alternative for old <strong>XMLHttpRequest</strong>. The fetch() method always returns a promise allowing you to use asynchronous constructs like <strong>async/await</strong> or <strong>.then()/.catch()</strong> to handle the response.</p><p><strong>Basic Syntax</strong></p><p>fetch(&quot;https://somewebsite.com/users&quot;);</p><p>In a fetch() request, you pass the URL as the first argument. You can also include second optional parameter for additional settings like method, headers and request body.</p><p><strong>Handling Response</strong></p><pre>fetch(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; response.json());</pre><p>When request completes, the promise returns a Response object (even if response is an HTTP error like 404). This Response object provides information about the response, such as status, headers, and body.</p><p>The Response object’s body is a <strong>ReadableStream</strong>. That means the body contains the data, but it’s not directly accessible. You must use one of the following methods to parse the body</p><ul><li><strong>response.json() — </strong><em>for JSON data</em></li><li><strong>response.text() — </strong><em>for plain text</em></li><li><strong>response.blob() — </strong><em>for binary data</em></li><li><strong>response.arrayBuffer() — </strong><em>for raw binary data</em></li></ul><p>Above methods also return promises that resolve with the parsed data.</p><pre>eg: fetch(&quot;https://somewebsite.com/users&quot;).then(response =&gt; response.json());<br>eg: fetch(&quot;https://somewebsite.com/users&quot;).then(response =&gt; response.text());<br>eg: fetch(&quot;https://somewebsite.com/users&quot;).then(response =&gt; response.blob());<br>eg: fetch(&quot;https://somewebsite.com/users&quot;).then(response =&gt; response.arrayBuffer());</pre><p>Since these methods again return promises you have to handle it using another then().</p><pre>fetch(&quot;https://somewebsite.com/users&quot;) // returns promise we handle using .then()<br>.then(response =&gt; response.json()) // again returns promise we handle using .then()<br>.then(data =&gt; console.log(data));<br><br>fetch(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; response.text())<br>.then(data =&gt; console.log(data));<br><br>fetch(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; response.blob())<br>.then(data =&gt; console.log(data));<br><br>fetch(&quot;https://somewebsite.com/users&quot;)<br>.then(response =&gt; response.arrayBuffer())<br>.then(data =&gt; console.log(data));</pre><p><strong>Error Handling</strong></p><p>fetch() has a simple syntax but requires manual handling of some aspects, such as parsing JSON responses or handling errors. fetch() does not automatically throw an error for <strong>non-2xx status </strong>codes (It only rejects the Promise if there’s a <strong>network error).</strong> So we have to manually handle it via <strong>if (!response.ok)</strong></p><pre>fetch(&quot;https://somewebsite.com/users&quot;)<br>   .then(response =&gt; {<br>        if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>        return response.json();<br>    })<br>   .then(data =&gt; console.log(data))<br>   .catch(error =&gt; console.error(error));</pre><h4><strong>Sample requests with fetch() with .then()</strong></h4><p>1️⃣<strong>GET</strong></p><pre>fetch(&quot;https://somewebsite.com/users&quot;, {<br>    method:&#39;GET&#39;,<br>    headers:{&#39;Content-Type&#39;:&#39;application/json&#39;},<br>})<br>.then(response =&gt; {<br>    if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>    return response.json();})<br>.then(data =&gt; console.log(data))<br>.catch(error =&gt; console.error(error));<br><br>// or you can just<br><br>fetch(&quot;https://somewebsite.com/users&quot;)<br> .then(response =&gt; {<br>      if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>      return response.json();<br>  })<br> .then(data =&gt; console.log(data))<br> .catch(error =&gt; console.error(error));</pre><p>You don’t need to explicitly specify the <strong>method: &#39;GET&#39;</strong> or set <strong>Content-Type</strong> headers for GET requests, as there is no request body. But when you are fetching requests other than GET, you need these.</p><blockquote>You can add more than one header attributes if you need. It is common to customize headers when working with APIs that require authentication or need to receive specific content types.</blockquote><pre>headers: {<br>        &#39;Authorization&#39;: &#39;Bearer ACCESS_TOKEN&#39;,<br>        &#39;Accept&#39;: &#39;application/json&#39;,<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },</pre><p>2️⃣<strong>POST</strong></p><pre>fetch(&quot;https://somewebsite.com/add&quot;, {<br>    method:&#39;POST&#39;,<br>    headers:{&#39;Content-Type&#39;:&#39;application/json&#39;},<br>    body:JSON.stringify({<br>          //data you want to send<br>      }),<br>    })<br>.then(response =&gt; {<br>    if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>    return response.json()})<br>.then(data =&gt; console.log(data))<br>.catch(error =&gt; console.error(error));</pre><p>Why do we need to use <strong>body: JSON.stringify(data)</strong> instead of just sending <strong>body: data</strong> to the server ?</p><blockquote>Because fetch() <strong>doesn’t automatically convert</strong> JavaScript objects into JSON. When you set the <strong>Content-Type</strong> as <strong>application/json</strong> server expects request body to be JSON If you passed an object directly, you&#39;d get an error like:</blockquote><pre> TypeError: Failed to execute ‘fetch’: body is not a valid type</pre><p>3️⃣<strong>PUT</strong></p><pre>fetch(&quot;https://somewebsite.com/update/1&quot;, {<br>    method:&#39;PUT&#39;,<br>    headers:{&#39;Content-Type&#39;:&#39;application/json&#39;},<br>    body:JSON.stringify({<br>          //data you want to send<br>      }),<br>    })<br>.then(response =&gt; {<br>    if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>    return response.json()})<br>.then(data =&gt; console.log(data))<br>.catch(error =&gt; console.error(error));</pre><p>4️⃣<strong>DELETE</strong></p><pre>fetch(&quot;https://somewebsite.com/delete/1&quot;, {<br>    method:&#39;DELETE&#39;,<br>  })<br>.then(response =&gt; {<br>    if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br>    return response.json()})<br>.then(data =&gt; console.log(data))<br>.catch(error =&gt; console.error(error));</pre><p>We can use <strong>async/await </strong>for more readable code instead of .then() chaining. It allows asynchronous code to behaves like synchronous. <strong>await</strong> pauses method until the promise resolves. It is better to use <strong>async/await</strong> over <strong>.then()/.catch()</strong> since it makes easy to use conditionals , <strong>try/catch </strong>is simpler than chained <strong>.catch()</strong></p><pre>async function getUsers() {<br>  const response = await fetch(&quot;https://somewebsite.com/users&quot;);<br>  const data = await response.json();<br>  console.log(data);<br>}<br><br>getUsers();</pre><p><strong>await fetch(..)</strong> waits for the response from the backend and <strong>await response.json()</strong> waits for the body to be parsed as JSON. We must mark function <strong>async </strong>to use <strong>await </strong>later.</p><p>As mentioned earlier, fetch() does not throw an error for non-2xx status codes. Therefor here also we must explicitly check response with <strong>if (!response.ok)</strong></p><pre>async function getUsers() {<br>  try {<br>    const response = await fetch(&quot;https://somewebsite.com/users&quot;);<br><br>     if (!response.ok) { throw new Error(&#39;Invalid Response&#39;);}<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>getUsers();</pre><h4><strong>Sample requests with fetch() with async/await</strong></h4><p>1️⃣<strong>GET</strong></p><pre>async function getUsers() {<br>  try {<br>    const response = await fetch(&quot;https://somewebsite.com/users&quot;, {<br>        method:&#39;GET&#39;,<br>        headers:{&#39;Content-Type&#39;:&#39;application/json&#39;}})<br><br>    if (!response.ok) throw new Error(&#39;Invalid Response&#39;);<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>// or you can just<br><br>async function getUsers() {<br>  try {<br>    const response = await fetch(&quot;https://somewebsite.com/users&quot;);<br>    <br>    if (!response.ok) throw new Error(&#39;Invalid Response&#39;);<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>Here also no need to explicitly specify the <strong>method: &#39;GET&#39;</strong> or set <strong>Content-Type</strong> headers for GET requests, as there is no request body</p><p>2️⃣<strong>POST</strong></p><pre>async function addUser(userData) {<br>  try {<br>    const response = await fetch(&quot;https://somewebsite.com/add&quot;, {<br>      method: &#39;POST&#39;,<br>      headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>      body: JSON.stringify(userData),<br>    });<br><br>    if (!response.ok) throw new Error(&#39;Invalid Response&#39;);<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>3️⃣<strong>PUT</strong></p><pre>async function updateUser(id, updatedData) {<br>  try {<br>    const response = await fetch(`https://somewebsite.com/update/${id}`, {<br>      method: &#39;PUT&#39;,<br>      headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>      body: JSON.stringify(updatedData),<br>    });<br><br>    if (!response.ok) throw new Error(&#39;Invalid Response&#39;);<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>4️⃣<strong>DELETE</strong></p><pre>async function deleteUser(id) {<br>  try {<br>    const response = await fetch(`https://somewebsite.com/delete/${id}`, {<br>      method: &#39;DELETE&#39;,<br>    });<br><br>    if (!response.ok) throw new Error(&#39;Invalid Response&#39;);<br><br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><ul><li><strong>Built-in</strong>: Requires no external dependencies, Compatible with all browsers.</li><li><strong>Lightweight</strong>: No library is required since it is a part of the JavaScript runtime.</li><li><strong>Promise-based</strong>: Supports async/await and handles asynchronous requests via promises.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a66822b950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Project Creation: Angular vs React]]></title>
            <link>https://medium.com/@rwijayabandu/basic-project-creation-angular-vs-react-b9e6edbec3b0?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e6edbec3b0</guid>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[project-creation]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[vite-plugin]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 16:17:41 GMT</pubDate>
            <atom:updated>2025-10-01T16:17:41.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTeN3w21PMfh6f-d6q_gyA.png" /></figure><h3><strong>Angular Project Creation</strong></h3><p>We typically create a new Angular project using CLI.</p><ol><li><strong>Prerequisites</strong></li></ol><p>Ensure <strong>Node.js</strong> and <strong>npm (Node Package Manager)</strong> are installed on your system.</p><p>2. <strong>Install Angular CLI</strong></p><p>npm install -g @angular/cli</p><p>3. <strong>Create a New Angular Project</strong></p><p>ng new my-app</p><p>4. <strong>During Project Creation, Angular CLI Will Ask Several Questions:</strong></p><p>Which stylesheet format would you like to use?</p><ul><li>CSS</li><li>Sass (SCSS)</li><li>Sass (Indented)</li><li>Less</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6x3LIMnSMye2097nAW227g.png" /></figure><p>Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njeaNndhTf4bX9WrImsghQ.png" /></figure><p>5. <strong>Post-Creation Defaults</strong></p><p>After creating the project</p><ul><li>npm install runs automatically, creating the node_modules folder.</li><li>Git is automatically initialized (git init).</li></ul><p>6. <strong>Run the Angular Project</strong></p><pre>cd my-app<br>ng serve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*hjtKfDrBX6OAVgyfpgdVog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*F1RJ447qdmQeZTseZ4jkRA.png" /></figure><blockquote>project will be run on port 4200 by default</blockquote><p>Default Port: 4200 URL: <a href="http://localhost:4200/">http://localhost:4200</a></p><p>if we want to assign a different port we can use</p><p>ng serve — port &lt;port-number&gt;</p><p>ng serve — port 4500</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*pNTNjgI515aUtDIGaeQICw.png" /></figure><p><strong>🔔 Important Note (Angular 17+)</strong></p><p>As of Angular <strong>v17</strong>, projects are <strong>standalone by default</strong> (using standalone components, not NgModules).</p><p><strong>⚙️ Common Variations of ng new</strong></p><p>You can customize project creation with various CLI flags:</p><p>. ng new my-app — routing this will add angular router setup and creates AppRoutingModule</p><p>. ng new my-app — standalone this will enables standalone components and no NgModules are generated</p><p>. ng new my-app — no-standalone this will enables NgModules and no standalone components are disabled</p><p>. ng new my-app — style=scss</p><p>. ng new my-app — style=sass</p><p>. ng new my-app — style=less</p><p>. ng new my-app — style=css this will set default stylesheet</p><p>. ng new my-app — skip-install this will avoid running npm install after project creation</p><p>. ng new my-app — skip-git this will avoid initializing git after project creation</p><p>. ng new my-app — directory=my-folder this will create the new project in a specified folder</p><h3><strong>React Project Creation</strong></h3><p>As of 2025, the most popular way to create a React project is using <strong>Vite</strong></p><h4><strong>React with Vite</strong></h4><p><strong>1. Prerequisites</strong></p><p>Ensure <strong>Node.js</strong> and <strong>npm</strong> are installed.</p><p><strong>2. Create React Project Using Vite</strong></p><p>npm create vite@latest my-app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*45oOmkkqF6oexumy-pHUWQ.png" /></figure><p><strong>3.</strong> <strong>During Setup, Vite Will Ask Several Questions:</strong></p><p>Select a framework:</p><ul><li>Vanilla</li><li>Vue</li><li><strong>React</strong></li><li>Preact</li><li>Lit</li><li>Svelte</li><li>Solid</li><li>Qwik</li><li>Angular</li><li>Marko</li><li>Others</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*kcv7liabjzWNdT1LkrTYcw.png" /></figure><p>Select a variant:</p><ul><li>TypeScript</li><li>TypeScript + SWC</li><li>JavaScript</li><li>JavaScript + SWC</li><li>React Router v7</li><li>TanStack Router</li><li>RedwoodSDK</li><li>RSC</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*qWUlI8usKnhrJAk4gKPwzQ.png" /></figure><p><strong>4.</strong> <strong>Run The Project</strong></p><pre>cd my-app<br>npm install<br>npm run dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*HcMEMfNFKAHmzrpH4QFdOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*LJctoQ3etcueQkEERqEndw.png" /></figure><blockquote>using Vite the project will be run on port 5173 by default</blockquote><p>Default Port: 5173 URL: <a href="http://localhost:5173/">http://localhost:5173</a></p><p>if we want to assign a different port we can use</p><p>npm run dev — — port= &lt;port-number&gt;</p><p>npm run dev — — port=3000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*V5TvPFOAE92C_Sd6h8fs3A.png" /></figure><h4><strong>Old Way: React with Create React App (CRA)</strong></h4><p><strong>1. Prerequisites</strong></p><p>Ensure <strong>Node.js</strong> and <strong>npm</strong> are installed.</p><p><strong>2. Create React Project</strong></p><p>npx create-react-app my-app</p><p><em>no need to run </em><em>npm install/</em><em>create-react-app automatically runs </em><em>npm install</em></p><p>3. <strong>Run the Project</strong></p><pre>cd my-app<br>npm start</pre><blockquote>using CRA the project will be run on port 3000 by default</blockquote><p>Default Port: 3000 URL: <a href="http://localhost:3000/">http://localhost:3000</a></p><p>⚙️ CRA Optional Variants</p><p>. npx create-react-app my-app — template typescript this will enable typescript in react project</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e6edbec3b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ternary Operator / Ternary Conditional Operator]]></title>
            <link>https://medium.com/@rwijayabandu/ternary-operator-ternary-conditional-operator-0c73a30cb67b?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c73a30cb67b</guid>
            <category><![CDATA[if-else]]></category>
            <category><![CDATA[short-circuiting]]></category>
            <category><![CDATA[conditional-operator]]></category>
            <category><![CDATA[javascript-operators]]></category>
            <category><![CDATA[ternary-operator]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 09:37:02 GMT</pubDate>
            <atom:updated>2024-09-27T09:37:02.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*HVxc_5AZayXLxlwuvX1emw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*iXql3LtPfOs7gNulBkHPSQ.png" /></figure><p>Ternary conditional operator is a ternary operator that used as a shorthand for if ….else condition <strong>(simplified If ….Else condition)</strong>. Typically uses as an alternative for If ….Else statement and can be used to replace multiple lines of code with a single line. It is the only JavaScript operator that takes three operands, a condition followed by ? then an expression to execute if the condition is true followed by : and expression to execute if the condition is false.</p><p>syntax : condition ? expressionIfTrue : expressionIfFalse</p><ol><li>A condition</li><li>An expression to execute if the condition is true</li><li>An expression to execute if the condition is false</li></ol><pre>//if else condition<br><br>let age = 17;<br><br>if (age &gt;= 18) {<br>  console.log(&quot;You are an adult.&quot;);<br>} else {<br>  console.log(&quot;You are a child.&quot;);<br>}<br><br>//ternary operator<br><br>let age = 17;<br><br>console.log(age &gt;= 18 ? &quot;You are an adult.&quot; : &quot;You are a child.&quot;);<br><br>age &gt;= 18 is the condition.<br>&quot;You are an adult.&quot; is the expression evaluated if the condition is true.<br>&quot;You are a minor.&quot; is the expression evaluated if the condition is false.</pre><p><em>function example</em></p><pre>function getAccessLevel(isAdmin) { <br>return isAdmin ? ‘Full Access’ : ‘Limited Access’;<br>} <br>console.log(getAccessLevel(true)); // Output: Full Access <br>console.log(getAccessLevel(false)); // Output: Limited Access</pre><h4>important considerations</h4><ol><li>Rather than false, null, NaN, 0, empty string (&quot;&quot;), and undefined considered as false expressions. If condition is any of these, the result will be the expression for the false case</li><li>Ternary conditional operator is <strong>commonly used to handle null values</strong></li></ol><pre>const getMessage = (user) =&gt; {<br>  const userName = user ? user.name : &quot;Guest&quot;;<br>  return `Welcome, ${userName}`;<br>};<br><br>console.log(getMessage({ name: &#39;Alice&#39; })); // Welcome, Alice<br>console.log(getMessage()); // Welcome, Guest</pre><h4>Chaining ternary operators</h4><p>Ternary conditional operator can be chained similar to if ….else chain.</p><pre>function example() {<br> return condition1 ? value1<br> : condition2 ? value2<br> : condition3 ? value3<br> : value4;<br>}<br><br>// same example using if else<br>function example() {<br> if (condition1) {<br> return value1;<br> } else if (condition2) {<br> return value2;<br> } else if (condition3) {<br> return value3;<br> } else {<br> return value4;<br> }<br>}</pre><ul><li>It is best <strong>suited for simple</strong> conditions but <strong>for more complicated</strong> logic it is often clearer and more maintainable to use if else condition</li><li>In addition to ternary operator, JavaScript provides <strong>Short Circuiting</strong> with logical operators (&amp;&amp; and ||) It <strong>evaluates only one</strong> expression and <strong>stops evaluation</strong> of expressions based on the result of the first operand while ternary operator always evaluates both branches.</li></ul><h4>AND operator (&amp;&amp;) example :</h4><p>If the first operand is false, the second operand is not evaluated because the overall result will be false</p><pre>const user = null;<br>const name = user &amp;&amp; user.name; // ‘name’ will be null </pre><p>user is null, so user.name is not evaluated</p><h4>OR operator (||) example :</h4><p>If the first operand is false, the second operand is not evaluated because the overall result will be true</p><pre>const isLoggedIn = true;<br>const message = isLoggedIn || ‘Please log in’; // message will be true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*EL1zAKnci-wvgXZPjb6EnQ.png" /><figcaption>Combining Ternary Operator and Short Circuiting</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c73a30cb67b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between var, let and const in JavaScript]]></title>
            <link>https://medium.com/@rwijayabandu/difference-between-var-let-and-const-in-javascript-9ff6e06a7f21?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff6e06a7f21</guid>
            <category><![CDATA[javascript-var-let-const]]></category>
            <category><![CDATA[const-keyword]]></category>
            <category><![CDATA[let-keyword]]></category>
            <category><![CDATA[const]]></category>
            <category><![CDATA[var]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 05:05:54 GMT</pubDate>
            <atom:updated>2024-08-25T05:05:54.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xgPxz_cvSeirEfMo77eCQ.png" /></figure><p>One of the main concepts in JavaScript is variable declaration. We use var, let and const to create variables in JavaScript. These words seem similar to anyone, but they differ in usage. Let’s discuss how they differ from each other, shedding light on their appropriate usage, and helping you make informed decisions when declaring variables.</p><h3>Var</h3><ul><li>Var is the oldest keyword used to declare variables. It has <strong>global scope</strong> and <strong>functional scope</strong>.</li><li>That means if you create a variable inside a function (functional scope) using var, you can only use it within the function. Outside the function variable is not accessible.</li><li>If you create variable outside of a function (global scope) that means class level, you can use it anywhere.</li></ul><pre>var globalVar = 10; // Declared in the global scope<br><br>function functionvar() {<br>    console.log(globalVar); // Outputs: 10<br>}<br>console.log(globalVar); // Outputs: 10</pre><pre>function functionvar() {<br> var localVar = 20; // Declared within the function scope<br> console.log(localVar); // Outputs: 20<br>}<br>console.log(localVar); // Error: localVar is not defined</pre><p><strong>var can be updated and re-declared</strong></p><ul><li>You can <strong>re-declare a variable</strong> in the <strong>same scope</strong> using var keyword.</li><li>Also you can <strong>re-declare a variable</strong> in <strong>different scope</strong> using var keyword.</li><li>And you can <strong>modify a variable</strong> in the <strong>same scope</strong> using var.</li><li>Var keyword has hoisting behavior with returning undefined. Variables declared with var are hoisted, which means they can be accessed before they are declared. Due to hoisting, it does not matter where we have declared the variables, the variable declarations move to the top of their scopes. It will give an <strong>undefined</strong> value until we initialize it</li></ul><pre>var number = 30;<br>console.log(number); // Outputs: 30<br><br>var number = 40; // Re-declaration in the same scope<br>console.log(number); // Outputs: 40</pre><pre>var value = 50; // Global scope<br><br>function functionvar() {<br>    var value = 60; // Re-declaration in local scope<br>    console.log(value); // Outputs: 60<br>}<br>console.log(value); // Outputs: 50</pre><pre>var count = 70;<br>console.log(count); // Outputs: 70<br><br>count = 80; // Modify the existing variable<br>console.log(count); // Outputs: 80</pre><pre>console.log(hoistedVar); // Outputs: undefined, due to hoisting<br><br>var hoistedVar = 90;<br><br>console.log(hoistedVar); // Outputs: 90</pre><h3>let</h3><ul><li>It was introduced in ECMAScript 6 as alternative to var. let keyword is an improved version of var.</li><li>let has <strong>block scope</strong>. A block is a group of code bounded by {} That means variable declared with let can only be accessible within the code block. Outside the block, it is not accessible</li></ul><pre>{<br>    let blockVar = 100; // Declared within the block<br>    console.log(blockVar); // Outputs: 100<br>}<br><br>console.log(blockVar); // Error: blockVar is not defined</pre><p><strong>let can be updated but not re-declared</strong></p><ul><li>You cannot <strong>re-declare a variable</strong> within the <strong>same scope</strong> using let keyword. But you can <strong>re-declare the variables</strong> with the same name in <strong>different scopes</strong>.</li><li>Remember you can <strong>modify a variable</strong> in the <strong>same scope</strong> using let.</li><li>Let keyword doesn’t support hoisting. It returns <strong>referenceError</strong></li></ul><pre>let number = 200;<br>console.log(number); // Outputs: 200<br><br>number = 300; // Update the variable<br>console.log(number); // Outputs: 300<br><br>let number = 400; // Error: Identifier &#39;number&#39; has already been declared</pre><pre>let value = 500; // Global scope<br><br>{<br>    let value = 600; // Re-declaration in local scope<br>   console.log(value); // Outputs: 600<br>}<br><br>console.log(value); // Outputs: 500</pre><pre>console.log(hoistedLet); // Error: Cannot access &#39;hoistedLet&#39; before initialization<br><br>let hoistedLet = 700;<br><br>console.log(hoistedLet); // Outputs: 700</pre><h3>Const</h3><ul><li>Const has all the properties of let keyword, but it is <strong>used to declare consonants</strong>. You <strong>can’t update the value of a const variable or re-declare variable after you assign it a value</strong>. You must assign a value to const variable when you declare it</li></ul><pre>const pi = 3.14; // Must initialize<br>console.log(pi); // Outputs: 3.14<br><br>const e; // Error: Missing initializer in const declaration</pre><p><strong>const cannot be updated or re-declared</strong></p><ul><li>Const also has <strong>block scope</strong> and can create consonants whose values cannot be changed after initializing.</li></ul><pre>{<br>    const max = 100;<br>    console.log(max); // Outputs: 100<br>}<br><br>console.log(max); // Error: max is not defined</pre><ul><li>You cannot modify the value of const keyword. But you can modify the values of an object that was created with const keyword. If a constant is an object, its properties can be added, updated, or removed.</li><li>Const keyword doesn’t support hoisting.</li></ul><pre>const gravity = 9.81;<br>console.log(gravity); // Outputs: 9.81<br><br>gravity = 10; // Error: Assignment to constant variable</pre><pre>const speed = 60;<br>console.log(speed); // Outputs: 60<br><br>const speed = 70; // Error: Identifier &#39;speed&#39; has already been declared<br>console.log(speed);</pre><pre>const user = { name: &quot;Alice&quot;, age: 25 };<br>console.log(user); // Outputs: { name: &#39;Alice&#39;, age: 25 }<br><br>user.age = 26; // Modifying the property of the object<br>console.log(user); // Outputs: { name: &#39;Alice&#39;, age: 26 }<br><br>user = { name: &quot;Bob&quot;, age: 30 }; // Error: Assignment to constant variable</pre><pre>console.log(hoistedConst); // Error: Cannot access &#39;hoistedConst&#39; before initialization<br><br>const hoistedConst = 42;<br><br>console.log(hoistedConst); // Outputs: 42</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Z-OY1jGejlaDa_pcQD0hg.jpeg" /></figure><h3>When to Use let, var and const</h3><ul><li>var can be risky because its scope is either global or within a function, which can lead to bugs. variables declared with var can lead to unexpected behavior and are generally not recommended.</li><li>Use let when you know a variable’s value might change later in your code.</li><li>Use const for variables that should never change once you set them.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff6e06a7f21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert number to string in JavaScript?]]></title>
            <link>https://medium.com/@rwijayabandu/how-to-convert-number-to-string-in-javascript-7c08e221e5b0?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c08e221e5b0</guid>
            <category><![CDATA[tostring]]></category>
            <category><![CDATA[tofixed]]></category>
            <category><![CDATA[number-to-text]]></category>
            <category><![CDATA[type-conversion]]></category>
            <category><![CDATA[number-conversion]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 11:52:57 GMT</pubDate>
            <atom:updated>2024-08-18T12:55:05.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mRCpBD5xrcLkArfOVxv2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*ORHl49UQdQAZJXFiUUw_TQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*ehNCaYWRc66ioA4CyNg6Ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*dpNvfKUUnBHVkQEMhOJjNw.png" /></figure><p>There are several ways to convert number into string in JavaScript. some are common but some are rare. But we can still use if we have no other options. Let’s discuss one by one.</p><ol><li>toString()</li><li>String() constructor</li><li>Concatenating an empty string</li><li>Template strings</li><li>toLocaleString()</li><li>Lodash library</li><li>toFixed()</li></ol><h3>toString()</h3><p>The toString() method is a built-in function of the JavaScript Number object that converts any number value into a string. This method provides a way to represent numeric values as strings, which can be particularly useful when formatting numbers for display or manipulation as text.</p><blockquote><strong>Syntax: number.toString(radix)</strong></blockquote><p>method can be used to convert a number from the decimal number system (base 10) to a string representing the number in other number systems.</p><p>radix (optional)- An integer between 2 and 36 that specifies the base of the number to use for the conversion. For example, base 2 for binary, base 8 for octal, base 10 for decimal, and base 16 for hexadecimal. If not provided, the default is base 10.</p><pre>let num = 123;<br><br>let txt = num.toString(); // default base value 10<br><br>let txtBinary = num.toString(2); // base 2 output - 1111011<br><br>let txtOctal = num.toString(8); // base 8   output- 173<br><br>let txtHex = num.toString(16); // base 16   output- 7B</pre><p>You can also call the toString() method directly on a number literal by wrapping the number in parentheses to avoid syntax errors.</p><pre>(280).toString(); output- 280<br><br>(170).toString();   output- 170<br><br>170.toString()     output- SyntaxError: Invalid or unexpected token</pre><h3>String() constructor</h3><p>The String() constructor in JavaScript is a built-in function that converts various types of values, including numbers, into string type. It accepts an integer or floating-point number as a parameter and converts it into string type</p><blockquote><strong>Syntax: String(value)</strong></blockquote><p>value can be a number, boolean, object…..</p><pre>let num = 123;<br><br>let txtInteger = String(num)     //     output- 123<br><br>let num = 123.4;<br><br>let txtDecimal = String(num)     //     output- 123.4</pre><pre>let bool = true;<br><br>let txtBool = String(bool);     // &quot;true&quot;<br><br><br>let obj = { name: &quot;Alice&quot;, age: 30};<br><br>let txtObj = String(obj);       // &quot;[object Object]&quot;<br><br><br>let arr = [1, 2, 3];<br><br>let txtArr = String(arr);      // &quot;1,2,3&quot;</pre><p><strong>Main Considerations</strong></p><ul><li>It does not perform any base conversions as toString() does.</li></ul><h3>Concatenating an Empty String</h3><p>Concatenate the empty string with the number, it will convert the whole number to a string. One of the easiest ways to convert any integer or floating-point number into a string.</p><blockquote><strong>Syntax: “ ”+num or num+ “ ”</strong></blockquote><pre>let num = 195;<br><br>let txt = “ ”+num         output - 195<br><br>let txt = “ ”+195           output - 195<br><br>let txt = “ ”+123.4         output- 123.4<br><br><br><br>let txt = num+“ ”           output - 195<br><br>let txt = 195+” ”           output - 195<br><br>let txt = 123.4 +” ”       output- 123.4</pre><h3>Template strings</h3><p>Entering a number directly inside a string to convert any integer or floating number into string, known as template literals, provide a flexible and powerful way to embed expressions within strings in JavaScript.</p><blockquote><strong>Syntax:`${num}`</strong></blockquote><p>The ${} syntax is used within backticks (`) to embed expressions into a string</p><pre>let num = 100;<br><br>let txt = `${num}`   output- 100<br><br>let txt = `${100}`;   output- 100<br><br>let txt = `${100.3}`   output- 100.3</pre><h3>toLocaleString()</h3><p>The toLocaleString() method converts a number into a string using a local language format</p><blockquote><strong>Syntax: number.toLocalString(locals, options)</strong></blockquote><p>locales (optional): A string representing the locale(s) to use. If omitted, the method uses the default locale of the JavaScript environment.</p><p>options (optional): An object with properties that specify the number formatting. These options include style, currency, minimumFractionDigits, maximumFractionDigits, and others.</p><pre>let num = 123;<br><br>let txt = num.toLocalString()     output- 123<br><br><br>let num = 123456.43;<br><br>let str = num.toLocaleString(); // Output may vary based on the locale, e.g., &quot;1,234,567.43&quot; in en-US<br><br><br>let amount = 123456.439;<br><br>let currencyStr = amount.toLocaleString(&#39;en-US&#39;, { style: &#39;currency&#39;, currency: &#39;USD&#39; });<br><br>output- &quot;$123,456.44&quot;</pre><h3>Lodash library _.toString()</h3><p>Lodash provides a _.toString() function, which is designed to convert numbers to strings. It takes integer,floating-point number or boolean and converts to string</p><pre>const _ = require(&quot;lodash&quot;);<br>console.log(_.toString(111));       output- 111<br>console.log(_.toString(111.11));     output- 111.11<br>console.log(_.toString(true));        output- true</pre><h3>toFixed()</h3><p>JavaScript Number object provides several methods that return string values. toFixed() will always return value as string but it is not recommended for number to string conversions. That is designed to format a number to a specified number of decimal places and return it as a string. It is primarily used for situations where precise decimal formatting is required, such as in financial calculations</p><blockquote><strong>Syntax: number.toFixed(digits)</strong></blockquote><p>It will convert a number to a string, but it also formats the number to a specific number of decimal places</p><pre>let num = 123;<br><br>let txt = num.toFixed(0); // 123<br><br>let txt = num.toFixed(2); // 123.00<br><br>let num = 123.456;<br><br>let str = num.toFixed(2);   output- 123.46</pre><p>It will round the number if necessary to meet the specified number of decimal places</p><p><strong>Main Considerations</strong></p><ul><li>Decimal Formatting- toFixed() is particularly useful when you need to ensure a number is formatted with a specific number of decimal places.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c08e221e5b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert String to number using AngularJs?]]></title>
            <link>https://medium.com/@rwijayabandu/how-to-convert-string-to-number-using-angularjs-eb4e2b68d4ac?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb4e2b68d4ac</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[type-conversion]]></category>
            <category><![CDATA[parseint]]></category>
            <category><![CDATA[parsefloat]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 08:06:50 GMT</pubDate>
            <atom:updated>2024-08-15T08:06:50.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*wWzok1Pz_QYzM8uA4l7o0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*An3laRTe1nZQ6B0YTlsZ4Q.jpeg" /></figure><p>There are several ways to convert string into number in Angular. some are common but some are rare. But we can still use if we have no other options. Let’s discuss one by one.</p><ol><li>parseInt()</li><li>parseFloat()</li><li>Number() constructor</li><li>Urnary + operator</li><li>Math.floor() and Math.round()</li><li>Lodash library</li></ol><h4>Categories of Type Conversion</h4><ol><li>Explicit type conversions means a developer intentionally converts one type into another using functions or constructors.</li><li>Implicit type conversions means programming languages controls type conversion automatically based on the context of the operation</li></ol><h3>parseInt()</h3><p>Angular has built-in functions for type conversions, such as parseFloat() and parseInt(). If the number is a decimal string type we can use parseFloat() to convert the string to number. Otherwise, if we want to convert a string without decimal values, we can use parseInt(). The parseInt() function is a standard JavaScript function that parses a string argument and returns an integer</p><blockquote><strong>Syntax: parseInt(string, radix)</strong></blockquote><p>string — the string that needs to be converted into a number. If the parameter is not a string, the function will automatically convert it to a string using the toString() method.</p><p>radix — optional integer that represents the root or base of a number. Ex:- 2 or 8 or 10. If nothing is given, the default value is 10</p><p><strong>parseInt() is useful when you want to parse a string and convert it into an integer. It is also important when we want to convert strings into numbers with different bases such as binary, octal</strong></p><pre>var no = parseInt(“String we want to convert…”);<br>angular.isNumber( no );<br><br>var str = &quot;123&quot;;<br>var num = parseInt(str, 10);    // Output: 123<br>angular.isNumber( num );<br><br>var str = &quot;1010&quot;;<br>var binaryNum = parseInt(str, 2);   // Output: 10<br>angular.isNumber( binaryNum );</pre><p>isNumber() checks whether the value is converted to a type of number or not. It returns a boolean value. When a value passed to the function is of type number, it will return true; otherwise, it will return false</p><p><strong>Main Considerations</strong></p><ul><li>If the number doesn’t start with a number, then the parseInt() will return a “NaN” as output. If the number is written as: “Hello 100”, it will returns a “NaN” output</li><li>If the number is written as: “100px” then the parseInt() will ignore the rest of string and return only the number part as output.</li></ul><pre>let input = &quot;ab123&quot;;<br>let invalidNum = parseInt(input, 10);  // Output: NaN<br><br>let input = &quot;100px&quot;;<br>let number = parseInt(input, 10) // Output: 100</pre><ul><li>The first char of the string cannot be converted into number The parseInt() function returns a NaN, after that, if there is a string that cannot be converted into a number, it ignores the rest of the string.</li><li>leading whitespace in the string is ignored.</li></ul><p><strong>We can handle NaN output using </strong><strong>isNaN() as below</strong></p><pre>let input = &quot;ab123&quot;;<br>let invalidNum = parseInt(input, 10);<br>if (isNaN(invalidNum)) {<br>  console.log(&quot;The string does not represent a valid number.&quot;);<br>} else {<br>  console.log(invalidNum);<br>}</pre><h3>parseFloat()</h3><p>The parseFloat() function is a standard JavaScript function that parses a string argument and returns number</p><blockquote><strong>Syntax: parseFloat(string)</strong></blockquote><p>string — the string that needs to be converted into a number. If the parameter is not a string, the function will automatically convert it to a string using the toString() method</p><pre>var no = parseFloat(&quot;String we want to convert…&quot;);<br>angular.isNumber( no );<br><br>let str = &quot;123.4&quot;;<br>let num = parseFloat(str);   // Output: 123.4</pre><p><strong>Main Considerations</strong></p><ul><li>If the number is written as: “100px” then the parseFloat() will ignore the rest of string and return only the number part as output.</li></ul><pre>let input = &quot;100px&quot;;<br>let number = parseFloat(input); // Output: 100<br><br>let input = &quot;1.23e4&quot;; // exponential notation<br>let exponentialNum = parseFloat(input);  // Output: 12300<br><br>let input = &quot;   45.67   &quot;;<br>let spacedNum = parseFloat(input);   // Output: 45.67</pre><ul><li>Leading whitespace is ignored.</li><li>The first char of the string cannot be converted into number The parseFloat() function returns a NaN. After that, if there is a string that cannot be converted into a number, it ignores the rest of the string.</li><li>can handle exponential notation, numbers with leading and trailing spaces</li></ul><p><strong>We can handle NaN output using </strong><strong>isNaN() as below</strong></p><pre>let input = &quot;ab123&quot;;<br>let invalidNum = parseFloat(input);<br>if (isNaN(invalidNum)) {<br> console.log(&quot;The string does not represent a valid floating-point number.&quot;);<br>} else {<br> console.log(invalidNum);<br>}</pre><h3>unary + operator</h3><p>This is the easiest way to convert to a number in JavaScript. Unary operator, meaning it operates on a single operand.</p><pre>let stringNumber = “123”;<br>let convertedNumber = +stringNumber // output is 123<br>let convertedNumber = +&#39;789&#39;; // output is 789<br>let convertedNumber = +&#39;ab&#39;; // output is NaN<br>let convertedNumber = +&#39;123ab&#39;; // output is NaN</pre><p>It has drawbacks.</p><ul><li>It can only convert integer type strings without decimal points. string must be a number type. If the string is not a number, the resultant would be NaN</li></ul><p><strong>Comparison with </strong><strong>parseInt() and </strong><strong>parseFloat()</strong></p><p>While parseInt() and parseFloat() are more explicit and can handle different formats and bases, the unary + operator is a simple way to convert a string to a number.</p><h3>Number() constructor</h3><p>It’s a built-in function that can convert various data types to numbers, including strings, booleans, and more complex types</p><blockquote>Syntax: Number(value)</blockquote><p>value — value that needs to be converted into a number. It can be string or boolean or object.</p><pre>Number(&#39;789&#39;);         // output is 789<br>Number(&#39;78.9&#39;);        // output is 78.9<br>Number(&#39;089&#39;);        // output is 89<br>Number(&#39;123e-1&#39;);       // 12.3, exponential notation<br>Number(&#39;&#39;);             // output is 0, empty string<br>Number(&#39;0x11&#39;);         // output is 17, hexadecimal<br>Number(&#39;0b11&#39;);         // output is 3, binary<br>Number(&#39;0o11&#39;);         // output is 9, octal<br>Number(&#39;abc&#39;);         // output is NaN, non-numeric string<br>Number(&#39;100a&#39;);         // output is NaN, invalid numeric string<br>Number(true);          // output is 1<br>Number(false);         // output is 0<br>Number(null);          // output is 0<br>Number(undefined);    // output is NaN<br>Number({ valueOf: () =&gt; &#39;789&#39; }); // output is 789, object with valueOf method</pre><p><strong>Main Considerations</strong></p><ul><li>If the given value is Boolean, — true is converted to 1 and false is converted to 0</li><li>If the given value is Null: it returns 0</li><li>If the given value is empty it returns 0</li><li>If the given value is undefined: it returns NaN</li><li>White spaces at the beginning and at the end of the string are ignored</li><li>Leading 0 is ignored</li><li>Strings looks like binary and octal types are supported</li><li>If the given value does not represent a valid number, it returns NaN.</li><li>If the given value is object the Number() function first calls the valueOf() method if that returns a value it converts it into a number. If not then the Number() function tries calling the toString() method to convert the Object to a string and then tries to convert that string to a number</li></ul><h3>Math.floor() and Math.round()</h3><p>Math functions used for converting float numbers to integers but also can be used for type conversion.</p><p>Math.floor() used to round a number down to the nearest integer less than or equal to the given number. Math.round()used to round a number to the nearest integer.</p><pre>let stringInput = ‘5.8’;<br>let numericFloor = Math.floor(stringInput); // Converts ‘5.8’ to 5<br><br>let stringInput = &#39;5.8&#39;;<br>let numericFloor = Math.round(stringInput); // Converts &#39;5.8&#39; to 6</pre><h3>Lodash library</h3><p>Lodash provides a _.toNumber() function, which is designed to convert values to numbers. It convert strings with or without whitespace can handle different formats</p><pre>import _ from &#39;lodash&#39;;<br>let aNumber = _.toNumber(‘43’);    // Output: 43<br>let floatNumber = _.toNumber(‘3.1’);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb4e2b68d4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy MERN Application to Heroku]]></title>
            <link>https://medium.com/@rwijayabandu/deploy-mern-application-to-heroku-64bc03ab365f?source=rss-8e2e1831b91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bc03ab365f</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[heroku-cli]]></category>
            <category><![CDATA[heroku-deployment]]></category>
            <dc:creator><![CDATA[Ravithamara]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 13:47:07 GMT</pubDate>
            <atom:updated>2024-02-11T13:47:07.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbb2fLij4WfwkSb5ZNid5w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*KsMZdLgNxIemvQTakRzVVA.png" /></figure><h4><a href="https://www.heroku.com/">Heroku</a> is a platform as a service (PaaS) that enables developers to deploy, manage, and scale applications entirely in the cloud.</h4><p>Known for its simplicity and ease of use, Heroku supports various programming languages, making it an ideal choice for deploying web applications. <br>you can only deploy backend and full stack projects to Heroku. But you can’t deploy frontend only without server<br>In this article, we’ll explore the process of deploying a MERN (MongoDB, Express.js, React.js, Node.js) stack application on Heroku.</p><h4><strong>Step 1: Set Up Your MERN Stack App</strong></h4><ul><li>Before deploying to Heroku, ensure your MERN stack application is fully functional</li><li>Verify that your MongoDB connection strings, Express server routes, and React components are working</li></ul><h4><strong>Step 2: Create a Heroku Account</strong></h4><ul><li>In order to deploy your application to Heroku, you must have a Heroku account.</li><li>If you don’t have a Heroku account, sign up at Heroku’s official website.</li><li>Select “Node.js” under the “Primary development language” section. After signing in, you’ll be ready to create a new application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1FDetcmiq-sMIcj4K57xw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*CcMzKFsfufAMREILT1gSkg.jpeg" /></figure><h4><strong>Step 3: Create application</strong></h4><ul><li>you can create Heroku app using either the Heroku <strong>app dashboard</strong> or the Heroku <strong>Command Line Interface (CLI)</strong>.</li><li>Download and install the Heroku <a href="https://devcenter.heroku.com/articles/heroku-cli">Command Line Interface (CLI)</a> from here. This tool will allow you to interact with Heroku services directly from your terminal.<br>Both methods achieve the same result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*tchwjQhihGknwFaHxACVWw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*rXWR0uITVHhyQf9z9zFMIw.jpeg" /></figure><p><strong>Heroku App Dashboard:</strong></p><p>-&gt; Log in to your Heroku account.<br>-&gt; On the Heroku dashboard, there is “New” button. <br>-&gt; Click on it and select “Create new app.”<br>-&gt; Enter a unique name for your app, and Heroku will automatically generate a URL based on that name.<br>-&gt; Click “Create app.”</p><p><strong>Heroku CLI:</strong></p><p>-&gt; Open your terminal or command prompt.<br>-&gt; login to Heroku run command : heroku login<br>-&gt; this will redirect you to a URL in the browser where you can log in. Once you’re finished you can continue in the terminal.<br>-&gt; Run the following command to create a new Heroku app:</p><p>heroku create app-name<br>-&gt; Replace “app-name” with your desired app name.</p><h4>Step 4: Add buildpack</h4><ul><li>Go to settings tab in dashboard and click “Add Buildpack”</li><li>Then select “Node.js” in the window and click “Add Buildpack” button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*0RH5aA2bFtXytHTFS0jVOA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*-Onqla_0rgp3pJZ_WS5VnA.jpeg" /></figure><h4>Step 5: Configure package.json</h4><ul><li>Heroku needs to know which dependencies to install and how to start your app. Update your package.json file</li></ul><pre>&quot;scripts&quot;: {<br> …<br> &quot;start&quot;: &quot;node server.js&quot;,<br> &quot;heroku-postbuild&quot;: &quot;NPM_CONFIG_PRODUCTION=false npm install npm &amp;&amp; run build&quot;<br> },</pre><ul><li>Heroku runs a post build, installs dependencies and runs a build of your project.</li><li>Then it starts your project with the start script</li></ul><h4>Step 6: Commit your changes and deploy your app to Heroku</h4><p>git add .<br>git commit -m &quot;prepare for heroku deploy&quot;<br>git push heroku master</p><h4>Step 7: Open Your App</h4><p>you can preview your site at the URL Heroku sent when you ran heroku create</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bc03ab365f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>