<?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 Yogesh D V on Medium]]></title>
        <description><![CDATA[Stories by Yogesh D V on Medium]]></description>
        <link>https://medium.com/@trymysolution?source=rss-b5172c0f3d25------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Yogesh D V on Medium</title>
            <link>https://medium.com/@trymysolution?source=rss-b5172c0f3d25------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:06:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trymysolution/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[Dynamic rows and columns nested]]></title>
            <link>https://trymysolution.medium.com/dynamic-rows-and-columns-nested-500bb65b3392?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/500bb65b3392</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Mon, 27 May 2024 10:52:42 GMT</pubDate>
            <atom:updated>2024-05-27T10:52:42.670Z</atom:updated>
            <content:encoded><![CDATA[<pre>const myData = [ { id: 1, title: &#39;Section 1&#39;, rows: [ { id: 11, data: &#39;Data 1.1&#39; }, { id: 12, data: &#39;Data 1.2&#39;, rows: [ // Nested rows within row 12 { id: 121, data: &#39;Nested data 1.2.1&#39; }, { id: 122, data: &#39;Nested data 1.2.2&#39;, rows: [ // Nested rows within nested row 122 { id: 1221, data: &#39;Deeply nested data 1.2.2.1&#39; }, { id: 1222, data: &#39;Deeply nested data 1.2.2.2&#39; }, ], }, ], }, ], }, { id: 2, title: &#39;Section 2&#39;, rows: [ { id: 21, data: &#39;Data 2.1&#39; }, { id: 22, data: &#39;Data 2.2&#39; }, ], }, ];<br><br>import React from &#39;react&#39;; const Grid = ({ data }) =&gt; { const renderRow = (row) =&gt; { return ( &lt;div key={row.id} className=&quot;col&quot;&gt; {Array.isArray(row.data) ? ( // Check for nested data &lt;div className=&quot;row&quot;&gt; {/* Container for nested rows */} {row.data.map(renderRow)} &lt;/div&gt; ) : ( &lt;p key={row.id}&gt;{row.data}&lt;/p&gt; )} &lt;/div&gt; ); }; return ( &lt;div className=&quot;container&quot;&gt; {data.map((section) =&gt; ( &lt;div key={section.id} className=&quot;row&quot;&gt; &lt;h2&gt;{section.title}&lt;/h2&gt; {/* Display section title */} {section.rows.map(renderRow)} &lt;/div&gt; ))} &lt;/div&gt; ); }; export default Grid;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=500bb65b3392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[when should and should not we prefer Lazy load for react component]]></title>
            <link>https://trymysolution.medium.com/when-should-and-should-not-we-prefer-lazy-load-for-react-component-4d2bf36f64d4?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d2bf36f64d4</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 13:53:33 GMT</pubDate>
            <atom:updated>2024-02-19T13:53:33.765Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>You should consider using lazy loading for React components in the following situations:</blockquote><p><strong>1. Components are not immediately visible or frequently used:</strong></p><ul><li>This is the most common use case for lazy loading. If a component is hidden from view on initial page load or only accessed occasionally, it makes sense to delay its loading until it’s actually needed. This reduces the initial bundle size and improves perceived performance for users, especially on slower connections.</li></ul><p><strong>2. Large or complex components:</strong></p><ul><li>Loading large components upfront can significantly impact initial page load times. By lazy loading such components, you minimize the initial footprint and ensure a smoother initial experience. This is especially relevant for components with extensive dependencies or heavy processing requirements.</li></ul><p><strong>3. Features based on user interactions:</strong></p><ul><li>If a component is displayed only after a specific user action, like clicking a button or navigating to a dedicated route, consider lazy loading it. This avoids unnecessarily loading unnecessary code for features the user might not even interact with.</li></ul><p><strong>4. Testing and development workflow:</strong></p><ul><li>Lazy loading can improve development and testing experiences by isolating specific components. You can test and debug individual components without loading the entire application, leading to faster feedback loops and more efficient development cycles.</li></ul><blockquote><strong>However, there are also some scenarios where lazy loading might not be the best solution:</strong></blockquote><p><strong>1. Critical components</strong>:</p><ul><li>Avoid lazy loading components that are essential for the core functionality of your application. This can lead to a noticeable delay when users first interact with them, impacting the overall user experience negatively.</li></ul><p><strong>2. Frequently used components</strong>:</p><ul><li>If a component is accessed frequently throughout the user journey, lazy loading might not provide significant benefits. The loading overhead might outweigh the initial bundle size reduction.</li></ul><p><strong>3. Simple or small components</strong>:</p><ul><li>The complexity of implementing lazy loading might outweigh the benefits for very small or simple components. Consider the trade-off between code footprint and development effort in such cases.</li></ul><p><strong>Ultimately, the decision to lazy load depends on your specific application’s needs and structure. Evaluate the size, usage frequency, and criticality of each component before deciding on the most suitable approach</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d2bf36f64d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between code splitting and lazy loading in react, both are not same ?]]></title>
            <link>https://trymysolution.medium.com/difference-between-code-splitting-and-lazy-loading-in-react-both-are-not-same-4a69f870fb9f?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a69f870fb9f</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 13:48:00 GMT</pubDate>
            <atom:updated>2024-02-19T13:48:00.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Difference between code splitting and lazy loading in react, both are not same ?</h3><p>Code splitting and lazy loading are both techniques used in React to optimize application performance by reducing the initial bundle size. While they are related, they serve different purposes and have distinct implementations</p><p><strong>Code Splitting:</strong></p><ul><li><strong>Concept:</strong> Breaks down your React application into smaller, independent bundles that can be loaded on demand.</li><li><strong>Implementation:</strong> Utilizes tools like Webpack or Rollup to create separate bundles for different parts of your application. You can use dynamic imports (import()) or component-based splitting techniques to define code splitting boundaries.</li><li><strong>Benefits:</strong> Reduces initial bundle size, leading to faster page load times. Improves perceived performance by loading code for features only when needed.</li><li><strong>Drawbacks:</strong> Introduces additional complexity in managing and loading bundles. Might require additional setup and configuration.</li></ul><p><strong>Lazy Loading:</strong></p><ul><li><strong>Concept:</strong> Defers the loading of specific components or features until they are actually required by the user.</li><li><strong>Implementation:</strong> Employs the React.lazy function to wrap components that should be lazy loaded. This creates a placeholder while the component code is fetched asynchronously.</li><li><strong>Benefits:</strong> Reduces initial bundle size even further compared to code splitting. Avoids loading unused components, enhancing performance.</li><li><strong>Drawbacks:</strong> Requires additional dependencies like Suspense components to handle loading states. Might introduce slight rendering delays when lazy-loaded components are accessed.</li></ul><p><strong>Choosing the Right Approach:</strong></p><ul><li>Use code splitting for larger features or sections of your application that are not immediately required by the user.</li><li>Use lazy loading for individual components that are not essential for the initial render or those accessed less frequently.</li><li>You can even combine both techniques. For example, code split a feature bundle and then lazy load individual components within that bundle.</li></ul><p><strong>In summary:</strong></p><ul><li>Code splitting focuses on dividing your application into independent bundles, while lazy loading delays loading specific components until needed.</li><li>Both techniques help optimize performance by reducing the initial bundle size, but they have different use cases and implementation details.</li><li>Choose the appropriate approach based on your specific needs and application structure.</li></ul><p>Here’s a table summarizing the key differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMjsqup1xiRrpoh2HY7F9Q.png" /></figure><p>I hope this clarifies the differences and helps you decide which technique best suits your React project!</p><h3><strong>Lazy Loading</strong></h3><p><strong>App.js:</strong></p><pre>import React, { Suspense } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>const About = React.lazy(() =&gt; import(&#39;./About&#39;));<br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;My React App&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; import(&#39;./About&#39;).then(() =&gt; console.log(&#39;About loaded&#39;))}&gt;<br>        Load About<br>      &lt;/button&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;About /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p><strong>About.js:</strong></p><pre>function About() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;About This App&lt;/h2&gt;<br>      &lt;p&gt;This is the About page.&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default About;</pre><h3>Code splitting</h3><p>Here’s an example of Webpack configuration for code splitting in your React project:</p><p><strong>webpack.config.js:</strong></p><p>Code split in to two bundles</p><pre>const path = require(&#39;path&#39;);<br>const webpack = require(&#39;webpack&#39;);<br>module.exports = {<br>  mode: &#39;development&#39;, // Adjust for production build if needed<br>  entry: {<br>    app: &#39;./src/App.js&#39;,<br>    about: &#39;./src/About.js&#39;, // Separate entry point for About component<br>  },<br>  output: {<br>    filename: &#39;[name].bundle.js&#39;,<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>  },<br>  optimization: {<br>    splitChunks: {<br>      chunks: &#39;all&#39;, // Split all chunks<br>      cacheGroups: {<br>        vendor: {<br>          test: /[\\/]node_modules[\\/]/, // Vendor bundle for dependencies<br>          name: &#39;vendors&#39;,<br>          priority: -10,<br>        },<br>        common: {<br>          minChunks: 2, // Split modules shared between at least 2 chunks<br>          name: &#39;common&#39;,<br>          priority: -5,<br>        },<br>      },<br>    },<br>  },<br>};</pre><p><strong>Explanation:</strong></p><ul><li>This configuration defines two entry points: app (main bundle) and about (separate bundle for the About component).</li><li>optimization.splitChunks enables code splitting based on shared modules and dependencies.</li><li>vendor and common cache groups create separate bundles for vendor modules and shared modules between chunks.</li><li>Adjust the configuration based on your specific project structure and splitting needs.</li></ul><p><strong>Remember:</strong></p><ul><li>You need to install necessary loaders (e.g., babel-loader) based on your project setup.</li><li>This is a basic example, and you might need to adapt it for more complex scenarios.</li></ul><p>React using Webpack dynamic imports without Suspense:</p><p><strong>App.js:</strong></p><pre>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>function App() {<br>  const loadAbout = async () =&gt; {<br>    const { About } = await import(/* webpackChunkName: &quot;About&quot; */&#39;./About&#39;); // Dynamically import About component<br>    return &lt;About /&gt;;<br>  };<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;My React App&lt;/h1&gt;<br>      &lt;button onClick={loadAbout}&gt;Load About&lt;/button&gt;<br>      {/* Render About component conditionally after loading */}<br>      {loadAbout() &amp;&amp; &lt;div&gt;{loadAbout()}&lt;/div&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>I hope this helps!</p><p>Thanks for reading !!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a69f870fb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Object.create In JavaScript? , any unique advantages over other ways]]></title>
            <link>https://trymysolution.medium.com/why-object-create-in-javascript-any-unique-advantages-over-other-ways-da71dbc736c3?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/da71dbc736c3</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 13:10:32 GMT</pubDate>
            <atom:updated>2024-02-19T13:18:59.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Object.create In JavaScript? , any unique advantages over other ways</h3><blockquote>In JavaScript, while there are multiple ways to create objects, Object.create offers some unique advantages in specific situations</blockquote><p><strong>1. Prototype Inheritance:</strong> The primary benefit of Object.create lies in its ability to easily establish prototype inheritance chains. You can explicitly specify the prototype object during creation, allowing newly created objects to inherit properties and methods from the specified prototype. This simplifies code when dealing with inheritance patterns.</p><p><strong>2. Avoiding Constructor Invocation:</strong> Unlike using constructor functions, Object.create bypasses the automatic invocation of the constructor. This can be useful when you only want to inherit properties and methods without executing specific logic within the constructor.</p><p><strong>3. Flexible Property Configuration:</strong> You can optionally pass a second argument to Object.create to define properties on the newly created object. This allows you to specify property attributes (writable, enumerable, configurable) directly during creation, providing more granular control.</p><p><strong>4. Chaining Inheritance:</strong> Object.create enables chaining inheritance by specifying another object as the prototype of the prototype you use. This allows you to create more complex inheritance hierarchies more easily.</p><blockquote>However, it’s essential to consider potential drawbacks before choosing Object.create:</blockquote><p><strong>1. Less Common Pattern:</strong> Constructor functions are the more traditional and familiar way to create objects in JavaScript. Using Object.create might seem less intuitive, especially for those new to the language.</p><p><strong>2. Potential Confusion:</strong> Due to its less frequent use, Object.create might introduce confusion in code reviews or collaboration as it&#39;s not as widely understood as constructors.</p><p><strong>3. Legacy Browser Support:</strong> While widely supported in modern browsers, Object.create might have limited compatibility with older browsers, requiring polyfills for consistent behavior.</p><p><strong>In conclusion:</strong></p><ul><li>Use Object.create when you specifically need to set up prototype inheritance or avoid constructor invocation, especially if you&#39;re comfortable with its approach.</li><li>For simpler object creation or broader compatibility, constructor functions remain a valid and recommended choice.</li><li>Carefully consider the use case and potential drawbacks before incorporating Object.create into your code.</li></ul><blockquote>Certainly! Here are code snippets demonstrating the four unique advantages of <em>Object.create</em>:</blockquote><p><strong>1. Prototype Inheritance:</strong></p><p>JavaScript</p><pre>// Define a &quot;Shape&quot; prototype<br>function Shape() {<br>  this.x = 0;<br>  this.y = 0;<br>}<br><br>Shape.prototype.move = function(dx, dy) {<br>  this.x += dx;<br>  this.y += dy;<br>  console.log(&quot;Shape moved!&quot;);<br>};<br>// Create a rectangle object inheriting from Shape<br>const rectangle = Object.create(Shape.prototype);<br>rectangle.width = 10;<br>rectangle.height = 5;<br>rectangle.move(5, 3); // Outputs &quot;Shape moved!&quot; and updates rectangle&#39;s position</pre><pre>+-----------------+<br>|   Shape         |<br>+-----------------+<br>      ^<br>      | (prototype)<br>      v<br>+-----------------+<br>|   Rectangle     |<br>+-----------------+<br>      ^<br>      | (prototype)<br>      v<br>+-----------------+<br>|   Circle         |<br>+-----------------+\</pre><p><strong>2. Avoiding Constructor Invocation:</strong></p><pre>// Define a Person constructor with unnecessary logic<br>function Person(name) {<br>  this.name = name;<br>  // Initialize some complex logic that you want to avoid here<br>}<br><br>// Create a person object without invoking the constructor<br>const john = Object.create({}, {<br>  name: {<br>    value: &quot;John&quot;,<br>    writable: true,<br>  },<br>});<br>console.log(john.name); // Outputs &quot;John&quot; without unnecessary logic execution</pre><p><strong>3. Flexible Property Configuration:</strong></p><pre>// Create a circle object with specific property attributes<br>const circle = Object.create({}, {<br>  radius: {<br>    value: 5,<br>    writable: false, // Make radius read-only<br>    configurable: false, // Prevent further changes to attributes<br>  },<br>  area: {<br>    get() {<br>      return Math.PI * this.radius * this.radius;<br>    },<br>    // No setter defined, making area read-only<br>  },<br>});<br>circle.radius = 10; // Error thrown due to writeable: false<br>console.log(circle.area); // Outputs correct area based on read-only radius</pre><p><strong>4. Chaining Inheritance:</strong></p><pre>// Define a &quot;Point&quot; prototype<br>function Point(x, y) {<br>  this.x = x;<br>  this.y = y;<br>}<br><br>// Define a &quot;ColorPoint&quot; prototype inheriting from Point<br>function ColorPoint(x, y, color) {<br>  Point.call(this, x, y); // Call Point constructor manually<br>  this.color = color;<br>}<br>ColorPoint.prototype = Object.create(Point.prototype); // Chained inheritance<br>// Create a colored point object<br>const coloredPoint = Object.create(ColorPoint.prototype, {<br>  x: {<br>    value: 10,<br>  },<br>  y: {<br>    value: 20,<br>  },<br>  color: {<br>    value: &quot;red&quot;,<br>  },<br>});<br>console.log(coloredPoint.x); // Outputs 10, inherited from Point<br>console.log(coloredPoint.color); // Outputs &quot;red&quot;, defined in ColorPoint</pre><p>Remember, these are just examples, and the specific use case will determine if Object.create is the most suitable approach for your project.</p><p>Thanks for reading !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da71dbc736c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Date as in YYYY-MM-DD hh:mm:ss Format or MM/DD/YYYY hh:mm:ss]]></title>
            <link>https://trymysolution.medium.com/javascript-date-as-in-yyyy-mm-dd-hh-mm-ss-format-or-mm-dd-yyyy-hh-mm-ss-a0c96e8fa888?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c96e8fa888</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 09:31:42 GMT</pubDate>
            <atom:updated>2023-04-11T09:56:40.011Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Javascript Date method is very crazy, we can achieve different date format with simple changes</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V1sC3Lfsm3A0EwVf" /><figcaption>Photo by <a href="https://unsplash.com/@loic?utm_source=medium&amp;utm_medium=referral">Djim Loic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Final code snippet here</h4><pre><br>function padTwoDigits(num: number) {<br>  return num.toString().padStart(2, &quot;0&quot;);<br>}<br><br>function dateInYyyyMmDdHhMmSs(date: Date, dateDiveder: string = &quot;-&quot;) {<br>  // :::: Exmple Usage ::::<br>  // The function takes a Date object as a parameter and formats the date as YYYY-MM-DD hh:mm:ss.<br>  // 👇️ 2023-04-11 16:21:23 (yyyy-mm-dd hh:mm:ss)<br>  //console.log(dateInYyyyMmDdHhMmSs(new Date()));<br><br>  //  👇️️ 2025-05-04 05:24:07 (yyyy-mm-dd hh:mm:ss)<br>  // console.log(dateInYyyyMmDdHhMmSs(new Date(&#39;May 04, 2025 05:24:07&#39;)));<br>  // Date divider<br>  // 👇️ 01/04/2023 10:20:07 (MM/DD/YYYY hh:mm:ss)<br>  // console.log(dateInYyyyMmDdHhMmSs(new Date(), &quot;/&quot;));<br>  return (<br>    [<br>      date.getFullYear(),<br>      padTwoDigits(date.getMonth() + 1),<br>      padTwoDigits(date.getDate()),<br>    ].join(dateDiveder) +<br>    &quot; &quot; +<br>    [<br>      padTwoDigits(date.getHours()),<br>      padTwoDigits(date.getMinutes()),<br>      padTwoDigits(date.getSeconds()),<br>    ].join(&quot;:&quot;)<br>  );<br>}<br></pre><h3>Here is full story</h3><p>First we have created padTwoDigits function to leading zero to the day, month, hours, minutes and seconds if the value is less than 10.means suppose date is 4th means we need it like 04 because the format we need like DD two digits same for month, hours, minutes and seconds</p><pre>function padTwoDigits(num: number) {<br>  return num.toString().padStart(2, &quot;0&quot;);<br>}</pre><p>Next</p><p>we need year, month, and day these we will get from Javascript Date function using date = new Date(); date.getFullYear , date.getMonth date.getDate same for hour hours, minutes, seconds date.getHours date.getMinutes date.getSeconds</p><p>suppose today date is 19th may 2023 and 10 AM by using above methods we get 2023, 5, 19 and 10 hours</p><p>in above for month we need to prepend 0 for month may using our padTwoDigits</p><p>lets join all using .join() method thats here final code snippet</p><pre>function padTwoDigits(num: number) {<br>  return num.toString().padStart(2, &quot;0&quot;);<br>}<br><br>function dateInYyyyMmDdHhMmSs(date: Date, dateDiveder: string = &quot;-&quot;) {<br>  <br>  return (<br>    [<br>      date.getFullYear(),<br>      padTwoDigits(date.getMonth() + 1),<br>      padTwoDigits(date.getDate()),<br>    ].join(dateDiveder) +<br>    &quot; &quot; +<br>    [<br>      padTwoDigits(date.getHours()),<br>      padTwoDigits(date.getMinutes()),<br>      padTwoDigits(date.getSeconds()),<br>    ].join(&quot;:&quot;)<br>  );<br>}</pre><blockquote><strong>:::: Exmple Usage ::::</strong></blockquote><p><em>The function </em><em>dateInYyyyMmDdHhMmSs takes a Date object as a parameter, divider ‘ — ’ or ‘ / ’ and formats the date as YYYY-MM-DD hh:mm:ss.</em></p><p>👇️ 2023–04–11 16:21:23 (yyyy-mm-dd hh:mm:ss)</p><p>console.log(dateInYyyyMmDdHhMmSs(new Date()));</p><p>2025–05–04 05:24:07 (yyyy-mm-dd hh:mm:ss)</p><blockquote>Its All Javascript we can pass required date as well 👇️️</blockquote><p>dateInYyyyMmDdHhMmSs(new Date(‘May 04, 2030 10:20:07’), &#39;/&#39;)</p><p>05/04/2030 10:20:07</p><h4>Date divider ‘ — ’ or ‘ / ’ we can pass param</h4><p>👇️ 01/04/2023 10:20:07 (MM/DD/YYYY hh:mm:ss)</p><p>console.log(dateInYyyyMmDdHhMmSs(new Date(), “/”));</p><blockquote><strong>Thanks for reading, and happy coding!!!!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c96e8fa888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Long nested/Multi dimensional Array to simple Array Javascript (Flattening an array)]]></title>
            <link>https://trymysolution.medium.com/convert-long-nested-array-to-simple-array-javascript-c8f1696c191b?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f1696c191b</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 16:27:42 GMT</pubDate>
            <atom:updated>2025-01-06T12:23:45.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.</p><p><strong>Final code Snippet</strong></p><pre>const arr = [1, 2, &#39;22&#39;,[[[[[[[[[[[1,33,44,[&#39;ddd&#39;], 5678]]]]]]]]]]], &#39;abbb&#39;, &#39;ccc&#39;, 1234];<br><br>const flat = String(arr).split(&#39;,&#39;).map((elm)=&gt;  {<br><br>    return  !isNaN(elm) ? Number(elm) : elm<br>    <br>})<br>console.log(flat)<br><br>:: outPut<br><br>[1, 2, 22, 1, 33, 44, &#39;ddd&#39;, 5678, &#39;abbb&#39;, &#39;ccc&#39;, 1234]<br><br>--- or ---<br><br>function flatten(arr){<br>      var newArr = []<br>   for(var i = 0; i &lt; arr.length; i++){<br>     if(Array.isArray(arr[i])){<br>        newArr = newArr.concat(flatten(arr[i]))<br>     } else {<br>        newArr.push(arr[i])<br>     }<br>  } <br>  return newArr;<br>  // add whatever parameters you deem necessary - good luck!<br>}</pre><h3><strong>Here is the story…</strong></h3><p>Before we dive into the process of how a JavaScript array can be flattened, let us understand what we are trying to achieve with an example.</p><p>Here is Array Example constarr</p><pre>const arr = [1, 2, &#39;22&#39;,[[[[[[[[[[[1,33,44,[&#39;ddd&#39;], 5678]]]]]]]]]]], &#39;abbb&#39;, &#39;ccc&#39;, 1234];<br></pre><p>To flatten above array first we need to convert array to string</p><pre>const flat = String(arr);<br><br><br>console.log(flat)<br>console.log(typeof flat)<br><br>::: output<br><br>&quot;37 1,2,22,1,33,44,ddd,5678,abbb,ccc,1234&quot;<br> string<br><br>--- or ---<br><br>function flatten(arr){<br>      var newArr = []<br>   for(var i = 0; i &lt; arr.length; i++){<br>     if(Array.isArray(arr[i])){<br>        newArr = newArr.concat(flatten(arr[i]))<br>     } else {<br>        newArr.push(arr[i])<br>     }<br>  } <br>  return newArr;<br>  // add whatever parameters you deem necessary - good luck!<br>}</pre><p>So.. we flatten nested array to simple string , its type is String, now its one dimensional</p><p>now again We need to convert into Array based on coma(‘,’),Here we can use Arrey.split it will return array type</p><pre>const arr = [1, 2, &#39;22&#39;,[[[[[[[[[[[1,33,44,[&#39;ddd&#39;], 5678]]]]]]]]]]], &#39;abbb&#39;, &#39;ccc&#39;, 1234]<br><br>console.log(typeof arr[0])//Number<br><br>var flat= String(a).split(&#39;,&#39;)<br><br>console.log(flat)<br><br>// output<br>//Number<br>[&#39;1&#39;, &#39;2&#39;, &#39;22&#39;, &#39;1&#39;, &#39;33&#39;, &#39;44&#39;,&#39;ddd&#39;, &#39;5678&#39;, &#39;abbb&#39;, &#39;ccc&#39;, &#39;1234&#39;]<br><br>--- or ---<br><br>function flatten(arr){<br>      var newArr = []<br>   for(var i = 0; i &lt; arr.length; i++){<br>     if(Array.isArray(arr[i])){<br>        newArr = newArr.concat(flatten(arr[i]))<br>     } else {<br>        newArr.push(arr[i])<br>     }<br>  } <br>  return newArr;<br>  // add whatever parameters you deem necessary - good luck!<br>}</pre><p>In above Example we have two data Types one is number and string elements, typeofarr[0] is number and arr[2] is string but we got all strings as output</p><p>soo… here we need to compare and pull back same data type using isNaN</p><p>isNaN() is javascript function to check Number or not</p><p>if it is number we will convert it using Number constructor</p><p>Finally….</p><pre>const arr = [1, 2, &#39;22&#39;,[[[[[[[[[[[1,33,44,[&#39;ddd&#39;], 5678]]]]]]]]]]], &#39;abbb&#39;, &#39;ccc&#39;, 1234];<br><br>const flat = String(arr).split(&#39;,&#39;).map((elm)=&gt;  {<br><br>    return  !isNaN(elm) ? Number(elm) : elm<br>    <br>})<br>console.log(flat)<br><br>:: outPut<br><br>[1, 2, &#39;22&#39;,[[[[[[[[[[[1,33,44,[&#39;ddd&#39;], 5678]]]]]]]]]]], &#39;abbb&#39;, &#39;ccc&#39;, 1234];</pre><p>output</p><pre>[1, 2, 22,1, 33, 44, &#39;ddd&#39;, 5678, &#39;abbb&#39;,&#39;ccc&#39;, 1234]</pre><p>code editor sample</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fglo3tfgA85seQM3YmAsGw.png" /></figure><p>Thanks for reading, and happy coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f1696c191b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node cache using in-process concept, optimize and speed up your app performance, its all Node’ js…]]></title>
            <link>https://trymysolution.medium.com/node-cache-using-in-process-concept-optimize-and-speed-up-your-app-performance-its-all-node-js-7e2f658f2d9a?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2f658f2d9a</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 12:22:14 GMT</pubDate>
            <atom:updated>2023-03-21T13:05:15.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node cache using in-process concept, optimize and speed up your app performance, its all Node’ js process</h3><p><em>To Store data in node server, using node global/process space or Caching is a common technique. It let us avoid slow operations by reusing previous results. In this page, i could mentioned the different options for storing data that is using node global/process</em></p><p>Visit <a href="https://trymysolution.medium.com/node-cache-using-in-memory-concept-optimize-and-speed-up-app-performance-4e0a6ae489cf">To Know about in-memory cache</a> my another page</p><blockquote><strong>in-process</strong> <strong>databases are generally used by applications that manage a large amount of data and depend on rapid response time. With that in mind, we can sum up the some major benefits of </strong>in-process<strong> databases:</strong></blockquote><ul><li>Fewer CPU round trips/processes, leading to faster transactions or queries</li><li>Faster reads/writes, ensuring multi-user concurrency, leading to lower spend on database infrastructure</li><li>Low latency and scalability</li><li>Simple data access retrieval</li></ul><p>Below is an example that demonstrates how effective in-process caching can be performed without requiring a convoluted setup process. This simple NodeJS code utilizes yo-cache and the in-process cache-aside pattern , in this section to speed up subsequent requests for HomePageData API.</p><blockquote>server.js</blockquote><pre>const express = require(&#39;express&#39;);<br>const fetch = require(&#39;node-fetch&#39;);<br>const YoCache = require(&#39;Yo-Cache.js&#39;);<br><br>// stdTTL is the default time-to-live for each cache entry<br>const myCache = new YoCache({ stdTTL: 600 });<br><br>// retrieve some data from an API<br>async function getHomepageData() {<br>  const response = await fetch(`https://mydomine.com/fetchHomepageData`);<br><br>  if (!response.ok) {<br>    throw new Error(response.statusText);<br>  }<br><br>  return await response.json();<br>}<br><br>const app = express();<br>app.get(&#39;/home&#39;, async (req, res) =&gt; {<br>  try {<br>    // try to get the homePageData from the cache<br>    let homepageData = myCache.get(&#39;homePageData&#39;);<br><br>    // if homePageData does not exist in the cache, retrieve it from the<br>    // original source and store it in the cache<br>    if (homepageData == null) {<br>      homepageData = await getHomepageData();<br>      // time-to-live is set to 9000 seconds. After this period<br>      // the entry for `homePageData` will be removed from the cache<br>      // and the next request will hit the API again<br>      myCache.put(&#39;homePageData&#39;, homepageData, 9000);<br>    }<br><br>    res.status(200).send(homepageData);<br>  } catch (err) {<br>    console.log(err);<br>    res.sendStatus(500);<br>  }<br>});<br><br>// RealTime when ever we need we can clear cache<br>app.get(&#39;/cleareCache&#39;, async (req, res) =&gt; {<br>  try {<br>    // try to get the clearing with del from the cache<br>    myCache.del(&#39;homePageData&#39;);<br>    res.status(200).send(homepageData);<br>  } catch (err) {<br>    console.log(err);<br>    res.sendStatus(500);<br>  }<br>});<br><br>const port = 3000;<br>app.listen(port, () =&gt; {<br>  console.log(`Server listening on http://localhost:${port}`);<br>});</pre><p>Caching is generally recommended for cases in which the state of the data at a particular point in the app rarely changes. Think lists of products, list of banners in homepage, country calling codes, or store locations. By way of example, for a recent feature,<strong><em> I needed to fetch a list of banners from an external API</em></strong>. The most efficient method was to make that API call once and store the response in a cache.</p><h3><em>“The most efficient method was to make that API call once and store the response in a </em>in-process, <em>use from there”</em></h3><blockquote><em>Yo-Cache.js</em></blockquote><pre>class Cache {<br>    constructor(time=3000) {<br>        this.cache = Object.create(null);<br>        this.expireTime = time<br>    }<br><br>    put =  async function (key, value, newTime=this.expireTime, timeoutCallback) {<br>        const time = newTime  * 1000;<br>        // if (_debug) {<br>        //     console.log(&quot;caching: %s = %j (@%s)&quot;, key, value, time);<br>        // }<br><br>        // if (typeof time !== &#39;undefined&#39; &amp;&amp; (typeof time !== &#39;number&#39; || isNaN(time) || time &lt;= 0)) {<br>        //   throw new Error(&#39;Cache timeout must be a positive number&#39;);<br>        // } else if (typeof timeoutCallback !== &#39;undefined&#39; &amp;&amp; typeof timeoutCallback !== &#39;function&#39;) {<br>        //   throw new Error(&#39;Cache timeout callback must be a function&#39;);<br>        // }<br><br>        var oldRecord = this.cache[key];<br>        if (oldRecord) {<br>            clearTimeout(oldRecord.timeout);<br>        }<br><br>        var record = {<br>            value: value,<br>            expire: time + Date.now(),<br>        };<br><br>        if (!isNaN(record.expire)) {<br>            record.timeout = setTimeout(<br>                function () {<br>                    this.del(key);<br>                    if (timeoutCallback) {<br>                        timeoutCallback(key, value);<br>                    }<br>                }.bind(this),<br>                time<br>            );<br>        }<br><br>        this.cache[key] = record;<br><br>        return value;<br>    };<br>    get = async function(key, expCallback) {<br>        var data = this.cache[key];<br>        if (typeof data != &quot;undefined&quot;) {<br>            if (isNaN(data.expire) || data.expire &gt;= Date.now()) {<br>                return data.value;<br>            } else {<br>                // free some space<br><br>                delete this.cache[key];<br>                if(typeof expCallback == &#39;function&#39;) await expCallback()<br>                <br>            }<br>        }<br>        return null;<br>    };<br>    del = function (key) {<br>        delete this.cache[key];<br>    };<br>}<br><br>module.exports = new Cache();<br>module.exports.Cache = Cache;</pre><p>Caching is a complex topic that should not be treated lightly. When implemented correctly, you will reap huge rewards, but it can easily be a source of grief if you adopt the wrong solution. I hope this article has helped steer you in the right direction regarding setting up, managing, and administering your application cache.</p><p>Visit <a href="https://trymysolution.medium.com/node-cache-using-in-memory-concept-optimize-and-speed-up-app-performance-4e0a6ae489cf">To Know about in-memory cache</a> my another page</p><p>Thanks for reading, and happy coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2f658f2d9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node cache using in memory concept, optimize and speed up app performance]]></title>
            <link>https://trymysolution.medium.com/node-cache-using-in-memory-concept-optimize-and-speed-up-app-performance-4e0a6ae489cf?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e0a6ae489cf</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 12:05:11 GMT</pubDate>
            <atom:updated>2023-03-21T13:04:29.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node cache using in memory concept, optimize and speed up your app performance, its all Node’ js Memory</h3><blockquote>To Store data in node server, Caching and using node global/process space is a common technique. It let us avoid slow operations by reusing previous results. In this page, i could mentioned the different options for storing data that is using cache and using node global/process</blockquote><p>Visit <a href="https://trymysolution.medium.com/node-cache-using-in-process-concept-optimize-and-speed-up-your-app-performance-its-all-node-js-7e2f658f2d9a">To Know about in process </a>my another page</p><p>Caching is generally recommended for cases in which the state of the data at a particular point in the app rarely changes. Think lists of products, list of banners in homepage, country calling codes, or store locations. By way of example, for a recent feature,<strong><em> I needed to fetch a list of banners from an external API</em></strong>. The most efficient method was to make that API call once and store the response in a cache.</p><blockquote>The most efficient method was to make that API call once and store the response in a in-memory.</blockquote><p>In-memory databases are generally used by applications that manage a large amount of data and depend on rapid response time. With that in mind, we can sum up the some major benefits of in-memory databases:</p><ul><li>Fewer CPU round trips/processes, leading to faster transactions or queries</li><li>Faster reads/writes, ensuring multi-user concurrency, leading to lower spend on database infrastructure</li><li>Low latency and scalability</li><li>Simple data access retrieval</li></ul><p>Below is an example that demonstrates how effective in-memory caching can be performed without requiring a convoluted setup process. This simple NodeJS code utilizes yo-cache and the in memory cache-aside pattern , in this section to speed up subsequent requests for HomePageData API.</p><p>server.js</p><pre>const express = require(&#39;express&#39;);<br>const fetch = require(&#39;node-fetch&#39;);<br>const YoCache = require(&#39;Yo-Cache.js&#39;);<br><br>// stdTTL is the default time-to-live for each cache entry<br>const myCache = new YoCache({ stdTTL: 600 });<br><br>// retrieve some data from an API<br>async function getHomepageData() {<br>  const response = await fetch(`https://mydomine.com/fetchHomepageData`);<br><br>  if (!response.ok) {<br>    throw new Error(response.statusText);<br>  }<br><br>  return await response.json();<br>}<br><br>const app = express();<br>app.get(&#39;/home&#39;, async (req, res) =&gt; {<br>  try {<br>    // try to get the homePageData from the cache<br>    let homepageData = myCache.get(&#39;homePageData&#39;);<br><br>    // if homePageData does not exist in the cache, retrieve it from the<br>    // original source and store it in the cache<br>    if (homepageData == null) {<br>      homepageData = await getHomepageData();<br>      // time-to-live is set to 9000 seconds. After this period<br>      // the entry for `homePageData` will be removed from the cache<br>      // and the next request will hit the API again<br>      myCache.put(&#39;homePageData&#39;, homepageData, 9000);<br>    }<br><br>    res.status(200).send(homepageData);<br>  } catch (err) {<br>    console.log(err);<br>    res.sendStatus(500);<br>  }<br>});<br><br>// RealTime when ever we need we can clear cache<br>app.get(&#39;/cleareCache&#39;, async (req, res) =&gt; {<br>  try {<br>    // try to get the clearing with del from the cache<br>    myCache.del(&#39;homePageData&#39;);<br>    res.status(200).send(homepageData);<br>  } catch (err) {<br>    console.log(err);<br>    res.sendStatus(500);<br>  }<br>});<br><br>const port = 3000;<br>app.listen(port, () =&gt; {<br>  console.log(`Server listening on http://localhost:${port}`);<br>});</pre><blockquote>Yo-Cache.js</blockquote><pre>class Cache {<br>    constructor(time=3000) {<br>        this.cache = Object.create(null);<br>        this.expireTime = time<br>    }<br><br>    put =  async function (key, value, newTime=this.expireTime, timeoutCallback) {<br>        const time = newTime  * 1000;<br>        // if (_debug) {<br>        //     console.log(&quot;caching: %s = %j (@%s)&quot;, key, value, time);<br>        // }<br><br>        // if (typeof time !== &#39;undefined&#39; &amp;&amp; (typeof time !== &#39;number&#39; || isNaN(time) || time &lt;= 0)) {<br>        //   throw new Error(&#39;Cache timeout must be a positive number&#39;);<br>        // } else if (typeof timeoutCallback !== &#39;undefined&#39; &amp;&amp; typeof timeoutCallback !== &#39;function&#39;) {<br>        //   throw new Error(&#39;Cache timeout callback must be a function&#39;);<br>        // }<br><br>        var oldRecord = this.cache[key];<br>        if (oldRecord) {<br>            clearTimeout(oldRecord.timeout);<br>        }<br><br>        var record = {<br>            value: value,<br>            expire: time + Date.now(),<br>        };<br><br>        if (!isNaN(record.expire)) {<br>            record.timeout = setTimeout(<br>                function () {<br>                    this.del(key);<br>                    if (timeoutCallback) {<br>                        timeoutCallback(key, value);<br>                    }<br>                }.bind(this),<br>                time<br>            );<br>        }<br><br>        this.cache[key] = record;<br><br>        return value;<br>    };<br>    get = async function(key, expCallback) {<br>        var data = this.cache[key];<br>        if (typeof data != &quot;undefined&quot;) {<br>            if (isNaN(data.expire) || data.expire &gt;= Date.now()) {<br>                return data.value;<br>            } else {<br>                // free some space<br><br>                delete this.cache[key];<br>                if(typeof expCallback == &#39;function&#39;) await expCallback()<br>                <br>            }<br>        }<br>        return null;<br>    };<br>    del = function (key) {<br>        delete this.cache[key];<br>    };<br>}<br><br>module.exports = new Cache();<br>module.exports.Cache = Cache;</pre><p>Caching is a complex topic that should not be treated lightly. When implemented correctly, you will reap huge rewards, but it can easily be a source of grief if you adopt the wrong solution. I hope this article has helped steer you in the right direction regarding setting up, managing, and administering your application cache.</p><p>Visit <a href="https://trymysolution.medium.com/node-cache-using-in-process-concept-optimize-and-speed-up-your-app-performance-its-all-node-js-7e2f658f2d9a">To Know about in process </a>my another page</p><p>Thanks for reading, and happy coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e0a6ae489cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Object , Array creation And Conditional spread element,]]></title>
            <link>https://trymysolution.medium.com/conditional-object-array-creation-and-conditional-spread-element-871d916a3ded?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/871d916a3ded</guid>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 11:10:48 GMT</pubDate>
            <atom:updated>2023-03-21T11:19:49.535Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://stackoverflow.com/questions/47882784/conditional-spread-element">Conditional</a> Object , Array creation And <a href="https://stackoverflow.com/questions/47882784/conditional-spread-element">Conditional spread element</a></h3><blockquote>if you’re using ES2018, The spread operator ( ... ) allows us to expand Iterable into function calls, array literals, and object literals. Spread syntax allows for some really convenient handling and duplicating of datasets without the verbosity of alternatives such as Object.assign() or Array.slice().</blockquote><p>While recently i wanted to modify small code snippet, I picked up this nifty trick where one can conditionally apply an object property in JavaScript using ES6’s spread syntax.</p><p>Here is my realtime experience to show conditionally list of item while myAccount dropdown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*vPpSttQhAQkk6fD86gMSUA.png" /></figure><p>Here is my existing code</p><pre><br>.......<br>.....<br>const renderMyAccount = () =&gt; {<br>.......<br>.....<br>  const myAccount = [<br>    {<br>      name: &#39;Order Histry&#39;,<br>    },<br>    {<br>      name: &#39;Profile&#39;,<br>    },<br>    {<br>      name: &#39;Shipping &amp; Payment&#39;,<br>    },<br>    {<br>      name: &#39;Refer a Friend&#39;,<br>    },<br>    {<br>      name: &#39;Logout&#39;,<br>    },<br>  ]<br>  return myAccount.map((item)=&gt;(<br>    &lt;div&gt;<br>      {item.name}<br>    &lt;div&gt;<br>  );<br><br>}<br><br>.......<br>.....</pre><p>In my case i have show Refer a friend based on isReferAfriedEnabled switch flag</p><p>We can know simplified using ES6 conditional spread next but <strong>before that lets have a look <em>on here is the regular way of spread</em></strong></p><pre>const renderMyAccount = () =&gt; {<br>    ....<br>    ..<br>      const referfriend = []<br>      if (isReferAfriedEnabled) {<br>            referfriend.push({<br>            name: &#39;Refer a Friend&#39;,<br>          },);<br>        }<br>      const myAccount = [<br>        {<br>          name: &#39;Order Histry&#39;,<br>        },<br>        {<br>          name: &#39;Profile&#39;,<br>        },<br>        {<br>          name: &#39;Shipping &amp; Payment&#39;,<br>        },<br><br><br>        ...referfriend,<br><br>        {<br>          name: &#39;Logout&#39;,<br>        },<br>      ]<br>    <br>    }</pre><p>See here same thing how i simplified using ES6 conditional spread</p><pre>...(isReferAfriedEnabled ? [{<br>            name: &#39;Refer a Friend&#39;,<br>   }] : []),</pre><pre>// isReferAfriedEnabled from global state<br><br>const renderMyAccount = () =&gt; {<br>    ....<br>    ..<br>      <br>      const myAccount = [<br>        {<br>          name: &#39;Order Histry&#39;,<br>        },<br>        {<br>          name: &#39;Profile&#39;,<br>        },<br>        {<br>          name: &#39;Shipping &amp; Payment&#39;,<br>        },<br><br><br>        ...(isReferAfriedEnabled ? [{<br>            name: &#39;Refer a Friend&#39;,<br>          }] : []),<br><br><br>        {<br>          name: &#39;Logout&#39;,<br>        },<br>      ]<br>    <br>    }</pre><p>This code can feel clever and clear and may be difficult to perceive at first view, which is normally something I‘m opposed to using, but the value it makes in front of other developers is worthwhile in my experience. Once you wrap your head around it, you may find it useful too!!!</p><p>we can use same thing in <strong>Array</strong> as well</p><pre>// isReferAfriedEnabled from global state<br><br>const renderMyAccount = () =&gt; {<br>    ....<br>    ..<br>      <br>      const myAccount = [<br>          &#39;Order Histry&#39;,<br>          &#39;Profile&#39;,<br>          &#39;Shipping &amp; Payment&#39;,<br>        <br><br>        ...(isReferAfriedEnabled ? [<br>            &#39;Refer a Friend&#39;,<br>          ] : []),<br><br><br>        &#39;Logout&#39;<br>      ]<br><br>      return myAccount.map((itemNme)=&gt;(<br>          &lt;div&gt;<br>            {itemNme}<br>          &lt;div&gt;<br>        );<br>    <br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=871d916a3ded" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Event-loop with setTimeout Example]]></title>
            <link>https://trymysolution.medium.com/javascript-event-loop-with-settimeout-example-b717823e7bb6?source=rss-b5172c0f3d25------2</link>
            <guid isPermaLink="false">https://medium.com/p/b717823e7bb6</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Yogesh D V]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 15:53:17 GMT</pubDate>
            <atom:updated>2021-02-08T15:53:17.665Z</atom:updated>
            <content:encoded><![CDATA[<p>To understand this… lets quickly have look into how below code can be executed…</p><pre>console.log(&#39;line one started&#39;);<br>.<br>.<br>setTimeout(function(){<br>  console.log(&#39;may be after a sec&#39;);<br>},1000);<br>.<br>.<br>console.log(&#39;last line&#39;);<br>.<br>.<br>.<br>.<br>N-number of lines</pre><p>What happen if we run above javascript code…</p><blockquote>very first <strong><em>Global execution context (GEC)</em> </strong>will be created and that will be pushed inside the <strong>callstack.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*miEiLAtkG8RGWMdrYo0AFg.png" /></figure><blockquote>Now code will run line by line</blockquote><p>In console initially we can see first line output and last line output and later we can see timeout console print.because of javascript event loop.</p><h3>What is eventLoop?</h3><p>Above code Snippet we have the main function which has 2 console.log commands logging ‘….’ and ‘…’ to the console. Sandwiched between them is a setTimeout call which logs ‘B’ to the console with 0ms wait time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3C_k00Icon1T4mFkIyq6Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oFQv-uktevBfWO5mpalNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzFho3HTVSwNvMciby6i4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypiG8tpirOSJSNfZY_76YA.png" /></figure><ol><li>The call to the main function is first pushed into the stack (as a frame). Then the browser pushes the first statement in the main function into the stack which is console.log(‘line one started’). This statement is executed and upon completion that frame is popped out. Alphabet `line one started` is displayed in the console.</li><li>The next statement (setTimeout() with callback function() and 0ms wait time) is pushed into the call stack and execution starts. setTimeout function uses a Browser API to delay a callback to the provided function. The frame (with setTimeout) is then popped out once the handover to browser is complete (for the timer).</li><li>console.log(‘last line ’) is pushed to the stack while the timer runs in the browser for the callback function. In this particular case, as the delay provided was 0ms, the callback will be added to the message queue as soon as the browser receives it (ideally).</li></ol><blockquote>After the execution of the last statement in the main function, the main() frame is popped out of the call stack, thereby making it empty<strong>. For the browser to push any message from the queue to the call stack, the call stack has to be empty first. That is why even though the delay provided in the setTimeout() was 0 seconds</strong>, the callback has to wait till the execution of all the frames in the call stack is complete.</blockquote><blockquote>so thats why setTimeout takes more then given timeout</blockquote><p>5.</p><p>Now the callback is pushed into the call stack and executed. The alphabet ‘may be after 5 sec’ is display on the console. This is the event loop of javascript.</p><blockquote>This is the event loop of javascript.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b717823e7bb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>