<?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 Yogendra kinja on Medium]]></title>
        <description><![CDATA[Stories by Yogendra kinja on Medium]]></description>
        <link>https://medium.com/@yogi.kinja?source=rss-795ccb6d955c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0-Va2Dkjq40J6RpJVxCHWQ.jpeg</url>
            <title>Stories by Yogendra kinja on Medium</title>
            <link>https://medium.com/@yogi.kinja?source=rss-795ccb6d955c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:18:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yogi.kinja/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[Why ref OR useTemplateRef is Better Than Using document.querySelector in Vue 3]]></title>
            <link>https://medium.com/@yogi.kinja/why-ref-or-usetemplateref-is-better-than-using-document-queryselector-in-vue-3-715fb0488658?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/715fb0488658</guid>
            <category><![CDATA[usetemplateref]]></category>
            <category><![CDATA[ref]]></category>
            <category><![CDATA[vue-3]]></category>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Wed, 14 May 2025 20:06:00 GMT</pubDate>
            <atom:updated>2025-05-14T20:06:00.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZIvE_Di0fna0WHLbY4CKrg.png" /></figure><p>In the world of Vue 3, one question keeps popping up among developers, especially those transitioning from vanilla JavaScript or jQuery:</p><blockquote><em>“Why should I bother with </em><em>ref or </em><em>useTemplateRef when I can just use </em><em>document.querySelector?&quot;</em></blockquote><p>It’s a fair question. After all, querySelector is familiar, fast, and gets the job done. But in the world of <strong>Vue 3&#39;s Composition API</strong>, directly reaching for document.querySelector might not always be the best approach. In fact, doing so can lead to subtle bugs, unscalable code, and missed opportunities to fully embrace Vue&#39;s powerful reactive system.</p><p>Let’s break this down.</p><h3>The Old Way: document.querySelector</h3><p>In traditional JavaScript development, when you wanted to grab an element and do something with it, you’d do this:</p><pre>const element = document.querySelector(&#39;#myDiv&#39;);<br>element.textContent = &#39;Hello, World!&#39;;</pre><p>Simple, right?<br>But when you bring that habit into a Vue 3 project, things can get messy.</p><h3>The Vue 3 Way: ref and useTemplateRef</h3><p>Vue 3 encourages you to think in <strong>components</strong>, <strong>reactivity</strong>, and <strong>lifecycle hooks</strong>.</p><p>Here’s how you’d do the same thing the Vue way:</p><pre>&lt;template&gt;<br>  &lt;div ref=&quot;myDiv&quot;&gt;Hello Vue 3&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { ref, onMounted } from &#39;vue&#39;;<br><br>const myDiv = ref(null);<br><br>onMounted(() =&gt; {<br>  myDiv.value.textContent = &#39;Hello, World!&#39;;<br>});<br>&lt;/script&gt;</pre><p>Or, using the ergonomic <strong>useTemplateRef</strong> from VueUse:</p><pre>&lt;template&gt;<br> &lt;div v-bind=&quot;myDiv&quot;&gt;Hello Vue 3&lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>import { useTemplateRef } from &#39;@vueuse/core&#39;;<br>const myDiv = useTemplateRef();<br>&lt;/script&gt;</pre><h3>Why ref / useTemplateRef Is Better</h3><h3>1. Scoped to the Component</h3><p>When you use ref, you&#39;re only referencing elements inside your component.<br> document.querySelector reaches into the entire DOM, potentially clashing with other parts of your app.</p><p>Vue components are designed to be <strong>self-contained and reusable</strong>. Using global selectors breaks that isolation.</p><h3>2. Lifecycle Awareness</h3><p>In Vue 3, your DOM isn’t guaranteed to exist until after the onMounted lifecycle hook.<br> With ref, Vue takes care of this automatically.<br> With document.querySelector, you risk querying before the DOM is ready, leading to null errors or race conditions.</p><h3>3. Reactive DOM Reference</h3><p>ref is reactive.<br> If your component updates or rerenders the element (due to v-if, v-for, etc.), your ref will always point to the latest element.<br> document.querySelector gives you a <strong>static, non-reactive reference</strong> that can easily go stale.</p><h3>4. Cleaner, Declarative Code</h3><p>Vue is declarative by design.<br> Using ref or useTemplateRef makes your code predictable, readable, and idiomatic.</p><h3>When Can You Still Use document.querySelector?</h3><p>Of course, document.querySelector isn&#39;t evil. There are legitimate use cases where it&#39;s okay or even necessary:</p><ul><li>When accessing elements <strong>outside your component’s DOM tree</strong> (like a global modal or layout wrapper).</li><li>When integrating with <strong>third-party libraries</strong> that expect selectors.</li><li>During <strong>quick debugging or prototyping</strong>.</li></ul><p>But as a rule of thumb, prefer ref or useTemplateRef inside your component templates.</p><h3>Final Thoughts</h3><p>In Vue 3, embracing the Composition API and reactive patterns is key to writing maintainable, scalable apps.</p><p>If you find yourself reaching for document.querySelector inside your Vue components, pause and ask:</p><blockquote><em>“Can I do this the Vue way with </em><em>ref or </em><em>useTemplateRef?”</em></blockquote><p>More often than not, the answer is yes — and your future self (and your teammates) will thank you for it.</p><p>Thanks for reading🙏and good luck 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=715fb0488658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to clone an array in JavaScript]]></title>
            <link>https://medium.com/@yogi.kinja/how-to-clone-an-array-in-javascript-c333bf4bfb50?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c333bf4bfb50</guid>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 21:10:15 GMT</pubDate>
            <atom:updated>2023-08-23T21:10:15.916Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript has many ways to do anything. I’ve written on 10 Ways to Write pipe/compose in JavaScript, and now we’re doing arrays.</p><h3>1. Spread Operator (Shallow copy)</h3><p>Ever since ES6 dropped, this has been the most popular method. It’s a brief syntax and you’ll find it incredibly useful when using libraries like React and Redux.</p><pre>numbers = [1, 2, 3];<br>numbersCopy = [...numbers];</pre><p><strong>Note:</strong> This doesn’t safely copy multi-dimensional arrays. Array/object values are copied by <em>reference</em> instead of by <em>value</em>.</p><p>This is fine</p><pre>numbersCopy.push(4);<br>console.log(numbers, numbersCopy);<br>// [1, 2, 3] and [1, 2, 3, 4]<br>// numbers is left alone</pre><p>This is not fine</p><pre>nestedNumbers = [[1], [2]];<br>numbersCopy = [...nestedNumbers];</pre><pre>numbersCopy[0].push(300);<br>console.log(nestedNumbers, numbersCopy);<br>// [[1, 300], [2]]<br>// [[1, 300], [2]]<br>// They&#39;ve both been changed because they share references</pre><h3>2. Good Old for() Loop (Shallow copy)</h3><p>I imagine this approach is the <em>least</em> popular, given how trendy functional programming’s become in our circles.</p><p>Pure or impure, declarative or imperative, it gets the job done!</p><pre>numbers = [1, 2, 3];<br>numbersCopy = [];</pre><pre>for (i = 0; i &lt; numbers.length; i++) {<br>  numbersCopy[i] = numbers[i];<br>}</pre><p><strong>Note:</strong> This doesn’t safely copy multi-dimensional arrays. Since you’re using the = operator, it’ll assign objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><p>This is fine</p><pre>numbersCopy.push(4);<br>console.log(numbers, numbersCopy);<br>// [1, 2, 3] and [1, 2, 3, 4]<br>// numbers is left alone</pre><p>This is not fine</p><pre>nestedNumbers = [[1], [2]];<br>numbersCopy = [];</pre><pre>for (i = 0; i &lt; nestedNumbers.length; i++) {<br>  numbersCopy[i] = nestedNumbers[i];<br>}</pre><pre>numbersCopy[0].push(300);<br>console.log(nestedNumbers, numbersCopy);<br>// [[1, 300], [2]]<br>// [[1, 300], [2]]<br>// They&#39;ve both been changed because they share references</pre><h3>3. Good Old while() Loop (Shallow copy)</h3><p>Same as for—impure, imperative, blah, blah, blah…it works! ?</p><pre>numbers = [1, 2, 3];<br>numbersCopy = [];<br>i = -1;</pre><pre>while (++i &lt; numbers.length) {<br>  numbersCopy[i] = numbers[i];<br>}</pre><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><p>This is fine</p><pre>numbersCopy.push(4);<br>console.log(numbers, numbersCopy);<br>// [1, 2, 3] and [1, 2, 3, 4]<br>// numbers is left alone</pre><p>This is not fine</p><pre>nestedNumbers = [[1], [2]];<br>numbersCopy = [];</pre><pre>i = -1;</pre><pre>while (++i &lt; nestedNumbers.length) {<br>  numbersCopy[i] = nestedNumbers[i];<br>}</pre><pre>numbersCopy[0].push(300);<br>console.log(nestedNumbers, numbersCopy);<br>// [[1, 300], [2]]<br>// [[1, 300], [2]]<br>// They&#39;ve both been changed because they share references</pre><h3>4. Array.map (Shallow copy)</h3><p>Back in modern territory, we’ll find the map function. <a href="https://en.wikipedia.org/wiki/Morphism">Rooted in mathematics</a>, map is the concept of transforming a set into another type of set, while preserving structure.</p><p>In English, that means Array.map returns an array of the same length every single time.</p><p>To double a list of numbers, use map with a double function.</p><pre>numbers = [1, 2, 3];<br>double = (x) =&gt; x * 2;</pre><pre>numbers.map(double);</pre><h4>What about cloning??</h4><p>True, this article’s about cloning arrays. To duplicate an array, just return the element in your map call.</p><pre>numbers = [1, 2, 3];<br>numbersCopy = numbers.map((x) =&gt; x);</pre><p>If you’d like to be a bit more mathematical, (x) =&gt; x is called <a href="https://en.wikipedia.org/wiki/Identity_function"><em>identity</em></a>. It returns whatever parameter it’s been given.</p><p>map(identity) clones a list.</p><pre>identity = (x) =&gt; x;<br>numbers.map(identity);<br>// [1, 2, 3]</pre><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>5. Array.filter (Shallow copy)</h3><p>This function returns an array, just like map, but it’s not guaranteed to be the same length.</p><p>What if you’re filtering for even numbers?</p><pre>[1, 2, 3].filter((x) =&gt; x % 2 === 0);<br>// [2]</pre><p>The input array length was 3, but the resulting length is 1.</p><p>If your filter&#39;s predicate always returns true, however, you get a duplicate!</p><pre>numbers = [1, 2, 3];<br>numbersCopy = numbers.filter(() =&gt; true);</pre><p>Every element passes the test, so it gets returned.</p><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>6. Array.reduce (Shallow copy)</h3><p>I almost feel bad using reduce to clone an array, because it’s so much more powerful than that. But here we go…</p><pre>numbers = [1, 2, 3];</pre><pre>numbersCopy = numbers.reduce((newArray, element) =&gt; {<br>  newArray.push(element);</pre><pre>  return newArray;<br>}, []);</pre><p>reduce transforms an initial value as it loops through a list.</p><p>Here the initial value is an empty array, and we’re filling it with each element as we go. That array must be returned from the function to be used in the next iteration.</p><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>7. Array.slice (Shallow copy)</h3><p>slice returns a <em>shallow</em> copy of an array based on the provided start/end index you provide.</p><p>If we want the first 3 elements:</p><pre>[1, 2, 3, 4, 5].slice(0, 3);<br>// [1, 2, 3]<br>// Starts at index 0, stops at index 3</pre><p>If we want all the elements, don’t give any parameters</p><pre>numbers = [1, 2, 3, 4, 5];<br>numbersCopy = numbers.slice();<br>// [1, 2, 3, 4, 5]</pre><p><strong>Note:</strong> This is a <em>shallow</em> copy, so it also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>8. JSON.parse and JSON.stringify (Deep copy)</h3><p>JSON.stringify turns an object into a string.</p><p>JSON.parse turns a string into an object.</p><p>Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.</p><p><strong>Note: This one</strong> <strong>safely copies deeply nested objects/arrays</strong>!</p><pre>nestedNumbers = [[1], [2]];<br>numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));</pre><pre>numbersCopy[0].push(300);<br>console.log(nestedNumbers, numbersCopy);</pre><pre>// [[1], [2]]<br>// [[1, 300], [2]]<br>// These two arrays are completely separate!</pre><h3>9. Array.concat (Shallow copy)</h3><p>concat combines arrays with values or other arrays.</p><pre>[1, 2, 3].concat(4); // [1, 2, 3, 4]<br>[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]</pre><p>If you give nothing or an empty array, a shallow copy’s returned.</p><pre>[1, 2, 3].concat(); // [1, 2, 3]<br>[1, 2, 3].concat([]); // [1, 2, 3]</pre><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>10. Array.from (Shallow copy)</h3><p>This can turn any iterable object into an array. Giving an array returns a shallow copy.</p><pre>numbers = [1, 2, 3];<br>numbersCopy = Array.from(numbers);<br>// [1, 2, 3]</pre><p><strong>Note:</strong> This also assigns objects/arrays by <em>reference</em> instead of by <em>value</em>.</p><h3>Conclusion</h3><p>Well, this was fun ?</p><p>I tried to clone using just 1 step. You’ll find many more ways if you employ multiple methods and techniques.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c333bf4bfb50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript — For and For/in Vs For/each and For/of]]></title>
            <link>https://medium.com/@yogi.kinja/javascript-for-and-for-in-vs-for-each-and-for-of-4e8edefdab7?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e8edefdab7</guid>
            <category><![CDATA[for-in-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[foreach-loop]]></category>
            <category><![CDATA[for-of-loop]]></category>
            <category><![CDATA[for-loop]]></category>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 19:15:12 GMT</pubDate>
            <atom:updated>2022-04-26T19:15:12.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript — For and For/in Vs For/each and For/of</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7pfjNulYBQwC4sVRP_FXw.jpeg" /></figure><p>Hello,</p><p>There’s numerous ways to loop over arrays and objects in JavaScript that’s why sometime generates some confusion between them 😕</p><p>Let’s start with comparison</p><h3>Syntatic Overview</h3><p>The for and for/in looping constructs give you access to the index in the array, not the actual element.</p><pre><strong>const</strong> arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];</pre><pre><strong>// with for and for/in loop you can get element using arr[i]<br>for</strong> (<strong>let</strong> i = 0; i &lt; arr.length; ++i) {<br>  console.log(arr[i]);<br>}<br><br><strong>for</strong> (<strong>let</strong> i <strong>in</strong> arr) {<br>  console.log(arr[i]);<br>}</pre><p>forEach() and for/of, you get access to the array element itself.</p><p>*With forEach() you can access the array index i, with for/of you cannot.</p><pre><strong>const</strong> arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];</pre><pre><strong>// with for and for/of loop you can get element direclty<br></strong>arr.<strong>forEach</strong>((item, i) =&gt; console.log(item) );<br><br><strong>for</strong> (<strong>const</strong> item of arr) {<br>  console.log(arr[i]);<br>}</pre><h3>Empty/Undefined Element</h3><p>JavaScript arrays allow empty elements.</p><p>forEach() and for/in skip empty elements in the array, for and for/of do not.</p><pre><strong>const</strong> arr = [&#39;a&#39;,, &#39;c&#39;]; or <strong>const</strong> arr = [&#39;a&#39;, undefined,&#39;c&#39;]</pre><pre><strong>for</strong> (<strong>let</strong> i = 0; i &lt; arr.length; ++i) {<br>  console.log(arr[i]);<br>}<br><em>// Prints &quot;a, undefined, c&quot;</em><br><br>arr.forEach(v =&gt; console.log(v));<br><em>// Prints &quot;a, c&quot;</em><br><br><strong>for</strong> (<strong>let</strong> i <strong>in</strong> arr) {<br>  console.log(arr[i]);<br>}<br><em>// Prints &quot;a, c&quot;</em><br><br><strong>for</strong> (<strong>const</strong> v <strong>of</strong> arr) {<br>  console.log(v);<br>}<br><em>// Prints &quot;a, undefined, c&quot;</em></pre><h3>Async/Await and Generators</h3><p>Another edge case with forEach() is that it <a href="https://thecodebarbarian.com/basic-functional-programming-with-async-await.html">doesn&#39;t quite work right with async/await</a> or <a href="http://es2015generators.com/">generators</a>. If your forEach() callback is synchronous then it doesn&#39;t matter, but you can&#39;t use await within a forEach() callback.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Question for you</p><p>How can we get index in for/of loop? please think first…</p><p>.</p><p>.</p><p>.</p><p>Here is the answer</p><p>To access the current array index in a for/of loop, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries">the </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries">Array#entries() function</a>.</p><pre><strong>for</strong> (<strong>const</strong> [i, v] <strong>of</strong> arr.entries()) {<br>  console.log(i, v); <em>// Prints &quot;0 a&quot;, &quot;1 b&quot;, &quot;2 c&quot;</em><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNrfZxpQkGMd66w_zMG41g.jpeg" /></figure><p>Thank you for reading. I hope this helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e8edefdab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closure In Javascript]]></title>
            <link>https://medium.com/@yogi.kinja/closure-in-javascript-35fcf5930829?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/35fcf5930829</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript-closure]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 10:55:00 GMT</pubDate>
            <atom:updated>2022-04-21T10:55:00.902Z</atom:updated>
            <content:encoded><![CDATA[<p>How can we explain that what is the closure exactly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kf5E2TlOk9M7BmDYidM1ow.png" /></figure><p>Let’s close to closure</p><p>Suppose, you want to <strong>count the number of times user clicked a button</strong> on a webpage.</p><p>For this, you are triggering a function on <strong>onclick</strong> event of button to update the count of the variable</p><pre>&lt;button onclick=&quot;updateClickCount()&quot;&gt;click me&lt;/button&gt;</pre><h3>Now there could be many approaches like:</h3><p>think before go down</p><p>……………</p><p><strong>Approach — 1</strong></p><p>You could use a <strong>global variable</strong>, and a function to increase the <strong>counter</strong>:</p><pre>var counter = 0;<br><br> function updateClickCount() {<br>     ++counter;<br>     // Do something with counter<br> }</pre><p>But, the drawback is that <strong>any script on the page can change the counter, without calling </strong><strong>updateClickCount()</strong>. right?</p><p><strong>Approach — 2</strong></p><p>Now, you might be thinking of declaring the variable inside the function:</p><pre>function updateClickCount() {<br>     var counter = 0;<br>     ++counter;<br>     // Do something with counter<br> }</pre><p>But, hey! Every time updateClickCount() function is called, the <strong>counter is set to 1 again.</strong></p><p><strong>Approach — 3</strong></p><p>Thinking about <strong>nested functions</strong>?</p><p>Nested functions have access to the scope “above” them.</p><p>In this example, the inner function updateClickCount() has access to the counter variable in the parent function countWrapper():</p><pre>function countWrapper() {<br>     var counter = 0;<br>     function updateClickCount() {<br>         ++counter;<br>         // Do something with counter<br>     }<br>     updateClickCount();<br>     return counter;<br> }</pre><p>This could have solved the counter dilemma, if you could reach the updateClickCount() function from the outside and you also need to find a way to execute counter = 0 only once not everytime.</p><p><strong>Approach — 4</strong></p><p><strong>Closure to the rescue! (self-invoking function)</strong>:</p><pre>var updateClickCount = (function(){<br>     var counter = 0;<br><br>     return function(){<br>         ++counter;<br>         // Do something with counter<br>     }<br> })();</pre><p>The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.</p><p>This way updateClickCount becomes a function. The &quot;wonderful&quot; part is that it can access the counter in the parent scope.</p><p>This is called a <strong>JavaScript closure</strong>. It makes it possible for a function to have “<em>private</em>” variables.</p><p>The counter is protected by the scope of the anonymous function, and can only be changed using the updateClickCount() function!</p><p>Check basic example of closure</p><pre>&lt;script&gt;<br>var updateClickCount = (function(){<br>    var counter = 0;<br><br>    return function(){<br>        ++counter;<br>        document.getElementById(&quot;spnCount&quot;).innerHTML = counter;<br>    }<br>})();<br>&lt;/script&gt;<br><br>&lt;html&gt;<br>&lt;button onclick=&quot;updateClickCount()&quot;&gt;click me&lt;/button&gt;<br>&lt;div&gt; you&#39;ve clicked<br>    &lt;span id=&quot;spnCount&quot;&gt; 0 &lt;/span&gt; times!<br>&lt;/div&gt;<br>&lt;/html&gt;</pre><p>I hope i have explained to you what is exaclty the closure.</p><p>Thank you for reading. I hope this helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35fcf5930829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel — Service Container]]></title>
            <link>https://medium.com/@yogi.kinja/laravel-service-container-f5710616659?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5710616659</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[service-container]]></category>
            <category><![CDATA[laravel-service-container]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:35:48 GMT</pubDate>
            <atom:updated>2022-04-17T10:36:22.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel — Service Container</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*1GgajAubuMmQ0SLWsp264Q.jpeg" /></figure><p>Why and when I have to use service container in laravel</p><p>Hello,</p><p>This will very useful who cannot understand a point of Laravel’s binding system. Let’s start</p><p>Let’s say you have this simple class Foo stored in app directory:</p><pre>&lt;?php<br><br>namespace App;<br><br>class Foo<br>{<br>    public function hello()<br>    {<br>        return &#39;Hello World&#39;;<br>    }<br>}</pre><p>You can type hinted this class without binding it first in the container. Laravel will still be able to resolve this class.</p><p>Let’s say you type-hinted it like this in the routes:</p><pre>Route::get(&#39;/foo&#39;, function (App\Foo $foo) {<br>    return $foo-&gt;hello(); // Hello World<br>});</pre><p>We can even go further, let’s say this Foo class required another simple class Bar. Our Bar class looks like this:</p><pre>&lt;?php<br><br>namespace App;<br><br>class Bar<br>{<br>    public function hello()<br>    {<br>        return &#39;bar&#39;;<br>    }<br>}</pre><p>And our Foo class looks like this now:</p><pre>&lt;?php<br><br>namespace App;<br><br>class Foo<br>{<br>    public function __construct(Bar $bar)<br>    {<br>        $this-&gt;bar = $bar;<br>    }<br><br>    public function hello()<br>    {<br>        return $this-&gt;bar-&gt;hello();<br>    }<br>}</pre><p>Will Laravel be able to resolve the type-hinted Foo class now? YES! Laravel will still be able to resolve this Foo class.</p><p>Now the issue will come in when our Foo class needs slightly more complex dependencies that need to be configured. Imagine that our Foo class simply need the name of our application. Sure you can simply use config(&#39;app.name&#39;) within the class&#39;s method, but imagine that this can be an HTTP client that requires a configuration array to instantiate.</p><pre>&lt;?php<br><br>namespace App;<br><br>class Foo<br>{<br>    public function __construct($appName)<br>    {<br>        $this-&gt;appName = $appName;<br>    }<br><br>    public function hello()<br>    {<br>        return &quot;Hello {$this-&gt;appName}&quot;;<br>    }<br>}</pre><p>Will Laravel be able to solve this class now? NOPE. <a href="https://laravel.com/docs/5.6/container">Service Container</a> to the rescue! You can teach Laravel how to resolve this Foo class by binding it in service container. You can define the binding within the register method on app\Providers\AppServiceProvider.php file:</p><pre>public function register()<br>{<br>    $this-&gt;app-&gt;bind(\App\Foo::class, function ($app) {<br>        // Pass the application name<br>        return new \App\Foo($app-&gt;config[&#39;app.name&#39;]);<br>    });<br>}</pre><p>And sometimes, you don’t want multiple instances to be created. Like our Foo class for instance, there&#39;s no need for multiple instances for this kind of class. In this case, we can bind it with singleton method.</p><pre>$this-&gt;app-&gt;singleton(\App\Foo::class, function ($app) {<br>    return new \App\Foo($app-&gt;config[&#39;app.name&#39;]);<br>});</pre><p><strong>More Important Usage</strong></p><p>But the more important usage of this service container is that we can bind an interface to it’s implementation. Let’s say we have this PaymentProcessorInterface with pay method:</p><pre>&lt;?php</pre><pre>namespace App;</pre><pre>interface PaymentProcessorInterface<br>{<br>    public function pay();<br>}</pre><p>Then we have the implementation of this interface named StripeProcessor:</p><pre>&lt;?php</pre><pre>namespace App;</pre><pre>class StripeProcessor implements PaymentProcessorInterface<br>{<br>    public function pay()<br>    {<br>        return &#39;pay with stripe&#39;;<br>    }<br>}</pre><p>With service container, we can bind the PaymentProcessorInterface to StripeProcessor class:</p><pre>$this-&gt;app-&gt;bind(\App\PaymentProcessorInterface::class, function () {<br>    return new \App\StripeProcessor();<br>});</pre><p>We can then type-hinted PaymentProcessorInterface within our code:</p><pre>Route::get(&#39;/pay&#39;, function (App\PaymentProcessorInterface $paymentProcessor) {<br>    return $paymentProcessor-&gt;pay(); // pay with stripe<br>});</pre><p>This way we can easily swap the PaymentProcessorInterface implementation. Let&#39;s say we want to change the payment processor to Paypal then we have this PaypalProcessor class.</p><pre>&lt;?php</pre><pre>namespace App;</pre><pre>class PaypalProcessor implements PaymentProcessorInterface<br>{<br>    public function pay()<br>    {<br>        return &#39;pay with paypal&#39;;<br>    }<br>}</pre><p>All we have to do is update the binding:</p><pre>$this-&gt;app-&gt;bind(\App\PaymentProcessorInterface::class, function () {<br>    return new \App\PaypalProcessor();<br>});</pre><p>Hope this will be very helpful.<br>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5710616659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Interview Questions]]></title>
            <link>https://medium.com/@yogi.kinja/javascript-interview-questions-5fecc3439e3f?source=rss-795ccb6d955c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fecc3439e3f</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Yogendra kinja]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 12:15:36 GMT</pubDate>
            <atom:updated>2022-04-22T11:58:31.253Z</atom:updated>
            <content:encoded><![CDATA[<h4>Check the list of advance and tricky javascript questions you must prepare.</h4><blockquote><strong>1. Explain what a callback function is and provide a simple example</strong></blockquote><p>A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console <em>after</em> some operations have been completed.</p><pre>function modifyArray(arr, callback) {<br>  // do something to arr here<br>  arr.push(100);<br>  // then execute the callback function that was passed<br>  callback();<br>}<br><br>var arr = [1, 2, 3, 4, 5];<br><br>modifyArray(arr, function() {<br>  console.log(&quot;array has been modified&quot;, arr);<br>});</pre><blockquote><strong>2. Given a string, reverse each word in the sentence</strong></blockquote><p>For example “Welcome to this javascript Guide!”should be become “emocleW ot siht tpircsavaJ !ediuG</p><pre>var string = &quot;Welcome to this Javascript Guide!&quot;;<br><br>// Output becomes !ediuG tpircsavaJ siht ot emocleW<br>var reverseEntireSentence = reverseBySeparator(string, &quot;&quot;);<br><br>// Output becomes emocleW ot siht tpircsavaJ !ediuG<br>var reverseEachWord = reverseBySeparator(reverseEntireSentence, &quot; &quot;);<br><br>function reverseBySeparator(string, separator) {<br>  return string.split(separator).reverse().join(separator);<br>}</pre><blockquote><strong>3. How to empty an array in JavaScript?</strong></blockquote><pre>var arrayList =  [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;];</pre><p>How could you empty an array?</p><p>Method-1</p><pre>arrayList = [];</pre><p>Above code will set the variable arrayList to a new empty array. This is recommended if you don&#39;t have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList.</p><p>for instance</p><pre>var arrayList = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]; // Created array<br>var anotherArrayList = arrayList;  // Referenced arrayList by another variable<br>arrayList = []; // Empty the array<br>console.log(anotherArrayList); // Output [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]</pre><p>Method-2</p><pre>arrayList.length = 0;</pre><pre>Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the another reference variable which pointing to arrayList.</pre><pre>///////////////////////</pre><pre>var arrayList = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]; // Created array<br>var anotherArrayList = arrayList;  // Referenced arrayList by another variable<br>arrayList.length = 0; // Empty the array by setting length to 0<br>console.log(anotherArrayList); // Output []</pre><p>Method-3</p><pre>arrayList.splice(0, arrayList.length);</pre><pre>Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.</pre><pre>var arrayList = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]; // Created array<br>var anotherArrayList = arrayList;  // Referenced arrayList by another variable<br>arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0<br>console.log(anotherArrayList); // Output []</pre><p><strong>4. Given two strings, return true if they are anagrams of one another</strong></p><p>For example: Mary is an anagram of Army</p><pre>var firstWord = &quot;Mary&quot;;</pre><pre>var secondWord = &quot;Army&quot;;</pre><pre>isAnagram(firstWord, secondWord); // true</pre><pre>function isAnagram(first, second) {<br>// For case insensitivity, change both words to lowercase.<br>var a = first.toLowerCase();<br>var b = second.toLowerCase();</pre><pre>// Sort the strings, and join the resulting array to a string. Compare the results<br>a = a.split(&quot;&quot;).sort().join(&quot;&quot;);<br>b = b.split(&quot;&quot;).sort().join(&quot;&quot;);<br>return a === b;<br>}</pre><blockquote>5. How would you use a closure to create a private counter?</blockquote><pre>function counter() {<br>  var _counter = 0;<br>  // return an object with several functions that allow you<br>  // to modify the private _counter variable<br>  return {<br>    add: function(increment) { _counter += increment; },<br>    retrieve: function() { return &#39;The counter is currently at: &#39; + _counter; }<br>  }<br>}<br><br>// error if we try to access the private variable like below<br>// _counter;<br><br>// usage of our counter function<br>var c = counter();<br>c.add(5); <br>c.add(9); <br><br>// now we can access the private variable in the following way<br>c.retrieve(); // =&gt; The counter is currently at: 14</pre><blockquote><strong>6. Explain Hoisting in javascript.</strong></blockquote><figure><img alt="javascript hoisting" src="https://cdn-images-1.medium.com/max/1024/1*81Y6T8Bo_8ZD7cuvCYoAow.png" /></figure><p>This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.</p><pre>hoistedVariable = 3;<br>console.log(hoistedVariable); <em>// outputs 3 even when the variable is declared after it is initialized	</em><br><strong>var</strong> hoistedVariable;</pre><pre>hoistedFunction();  <em>// Outputs &quot; Hello world! &quot; even when the function is declared after calling</em>  <strong>function</strong> hoistedFunction(){    console.log(&quot; Hello world! &quot;); }<br></pre><pre><em>// Hoisting takes place in the local scope as well</em><br><strong>function</strong> doSomething(){<br>  x = 33;<br>  console.log(x);<br>  <strong>var</strong> x;<br>}</pre><pre>doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope</pre><ul><li><em>Note — Variable initializations are not hoisted, only variable declarations are hoisted:</em></li></ul><pre><strong>var</strong> x;<br>console.log(x); <em>// Outputs &quot;undefined&quot; since the initialization of &quot;x&quot; is not hoisted</em><br>x = 23;</pre><ul><li><em>Note — To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:</em></li></ul><pre>&quot;use strict&quot;;<br>x = 23; <em>// Gives an error since &#39;x&#39; is not declared</em><br><strong>var</strong> x;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fecc3439e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>