<?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 Sriram on Medium]]></title>
        <description><![CDATA[Stories by Sriram on Medium]]></description>
        <link>https://medium.com/@lrlcwq?source=rss-2b99a2c5bb7f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lsUWBlY35RlJzgURMCnF_g.png</url>
            <title>Stories by Sriram on Medium</title>
            <link>https://medium.com/@lrlcwq?source=rss-2b99a2c5bb7f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:13:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lrlcwq/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[Do you feel hungry even after eating?]]></title>
            <link>https://medium.com/@lrlcwq/do-you-feel-hungry-even-after-eating-49551c0f78fe?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/49551c0f78fe</guid>
            <category><![CDATA[satiety]]></category>
            <category><![CDATA[fibre]]></category>
            <category><![CDATA[protein]]></category>
            <category><![CDATA[healthy-lifestyle]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 13:46:41 GMT</pubDate>
            <atom:updated>2026-11-22T14:34:04.747Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lack of protein can be a reason</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsF-vyzgIKdqNt70xoorHw.png" /></figure><blockquote>This meal is actually extremely high cal, and I feel completely fine. I feel like I haven’t eaten anything. I feel like a big bottomless pit. But that’s what happens when you don’t have good quality food. It just kind of goes right through you and you feel like shit but then you also feel hungry.<br>- <a href="https://youtu.be/K5CEvF2GbDI?t=1376">Taken from Will Tennyson’s YouTube Video (Timestamp: 22:57)</a></blockquote><blockquote>So, we are like around 1,000 calories for lunch and it’s not a very filling meal. Not a lot of nutrients to it. You’re going to eat it, probably be hungry in like an hour or two. So, not ideal.<br>- <a href="https://youtu.be/HQ_7noX-2Qg?t=770">Taken from Will Tennyson’s YouTube Video (Timestamp: 12:54)</a></blockquote><p>If you feel hungry even after eating in ample quantity, it could be because your food is low in protein and fibre. A diet which is high in carbohydrates and fats is highly palatable which makes us eat more but they have less filling effect on our body, i.e. they have low satiety. We feel hungry soon.</p><p>This is where protein and fibre come into picture. They have high satiety and keep us full for longer. Protein also helps in muscle building and recovery when we exercise and it helps in muscle retention when we are trying to lose weight. Fibre helps in digestion of our meal, especially if it’s high in protein.</p><p><a href="https://www.mdanderson.org/cancerwise/how-much-protein-do-i-need-a-dietitian-answers.h00-159781179.html">Generally</a>, we require around 0.8g of protein per kilogram of our weight and around 1.2 to 1.5 if we exercise. For example, if you weigh 70 kilos, getting 56g of protein is essential and 84–105g if you exercise.</p><p>You can maintain a log to find out how much protein you are consuming in a day. You can check nutrition profile behind packaged food items to get an idea. The readings can be per 100g so make sure to calculate it accordingly.</p><p>For example, the following Instant Noodles give nutrition profile per 30g, while the packet is of 60g. So, if you consume the complete packet, you will be getting around 200cal and 6g protein.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRs1fhqNuHqYfLRGul18XQ.png" /><figcaption><a href="https://slurrpfarm.com/products/magic-masala-instant-millet-noodles?srsltid=AYCX9vLC7LN9w_ZfbFBp7dVMj37-Dstm68JcVRBXmhiU_R2knYtQ9h0X">Image Source</a></figcaption></figure><p>Maintaining a high protein diet as per our weight requirements can be difficult and this is where supplements can help. If you have no trouble digesting milk, you can try milk based protein supplement, known as Whey Protein. Here are some good options in India: <a href="https://shop.amul.com/en/product/amul-chocolate-whey-protein-34-g-or-pack-of-30-sachets">Amul Whey</a> (It goes out of stock quickly. Generally comes in stock on Friday night), <a href="https://nutrabay.com/product/nutrabay-gold-100-whey-protein-concentrate/?pId=6589930&amp;vId=9639848&amp;gad_source=1&amp;gad_campaignid=24260449409&amp;gbraid=0AAAAACyq1hSrcgAX_goOdPZtOiXAU1j62&amp;gclid=Cj0KCQiAworYBhDoARIsAP5ft3LELWyHp7Lhe__RvG_texSnKRx3V4pyostCaA90GJx3GWbhsWhoq-caAhocEALw_wcB&amp;pa_flavour=Cold+Coffee&amp;pa_weight=1+kg+%282.2+lb%29">Nutrabay</a>, <a href="https://www.amazon.in/Platinum-Protein-Isolate-Digestive-Supplement/dp/B07X2QKVXG/ref=ast_sto_dp_puis?th=1">Nakpro</a>, <a href="https://rippedupnutrition.com/products/whey-protein-isolate-core-series?variant=57641958178956">RUN</a>.</p><p>If you have trouble digesting milk, you can try plant based proteins. They are more affordable also. Their taste are generally not good so you can check their reviews before buying them. Here are some good options: <a href="https://nutrabay.com/product/nutrabay-gold-hydrolyzed-pea-protein/?pId=3302532&amp;vId=3581824&amp;pa_weight=1+kg+%282.2+lb%29&amp;pa_flavour=Kesar+Badam+Pista&amp;utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=ao_search_nb_cm2_Brand_Peaprotein_mn&amp;gad_source=1&amp;gad_campaignid=24222939303&amp;gbraid=0AAAAACyq1hQcBos608fhufcCkfuT-bsK1&amp;gclid=Cj0KCQiAworYBhDoARIsAP5ft3LQ4IvNCJ2BD2C-emAc8nr1Tt8o31y4dwleSznHsTVIkTso0HVnfhoaArIHEALw_wcB">Nutrabay</a>, <a href="https://www.amazon.in/stores/OriginNutrition/page/E06B9D55-2233-4655-BD8D-2609BD197C48">Origin Nutrition</a>, <a href="https://www.amazon.in/TrueBasics-Clean-Protein-Powder-Chocolate/dp/B0FMRVH8QB?th=1">TrueBasics</a>.</p><p>You can check the website <a href="https://www.trustified.in/proteinpowders">Trustified</a> which regularly investigates the qualities of different protein powders in India, and can buy the powder which has passed their test.</p><p>Note: If you are trying to lose weight and maintaining calorie deficit by eating less, you will feel hungry even after eating a high protein diet but it will be not as extreme if you were on a low-protein diet. It is also advisable to get your blood checkup done and consult a doctor to know if your kidneys can take the load of increased protein diet. You can try <a href="https://www.1mg.com/labs?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign={1mg_labs_performance_max_Delhi_New}&amp;utm_adgroup={adgroup}&amp;utm_keyword=&amp;wpsrc=Google%20AdWords&amp;wpcid=24065382184&amp;wpsnetn=x&amp;wpkwn=&amp;wpkmatch=&amp;wpcrid=&amp;wpscid=&amp;wpkwid=&amp;gad_source=1&amp;gad_campaignid=24055828521&amp;gbraid=0AAAAADlmCdDZXspq5T_7kQ0BzJAhiEaVR&amp;gclid=Cj0KCQiAworYBhDoARIsAP5ft3KwiCx0kPHstxfMNc8lTeJ7KrlNPc6NUDJDdpzB4HrNwHoPrqIdsLAaAoEOEALw_wcB">Tata 1mg</a> to get your pathology test done at affordable rates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49551c0f78fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js Notes — Code Step by Step YT Channel]]></title>
            <link>https://medium.com/@lrlcwq/node-js-notes-code-step-by-step-yt-channel-0af44008da0d?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0af44008da0d</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 10:32:22 GMT</pubDate>
            <atom:updated>2025-02-24T07:14:08.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node.js Notes — Code Step by Step YT Channel</h3><h4>Working of Node.js, Template Engines, Middlewares, MongoDB, Mongoose, Events, OS Module, Multr Module</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HHBt5HacwQCiiXfjhSxKw.png" /></figure><p>Notes were prepared while following the first 54 videos of the series: <a href="https://www.youtube.com/playlist?list=PL8p2I9GklV456iofeMKReMTvWLr7Ki9At">Node.js tutorial in Hindi from ‘Code Step By Step’ YouTube channel</a>.</p><p>When we run a statement in JS which does’t return anything, undefined is printed.</p><p>When we do stuff like this:<br>const myfunc = require (&#39;fs&#39;).writeFile;<br>It actually returns the writeFile property of the object returned from fs module (writeFile property happens to be a fuction).</p><p>http module handles server requests and responses<strong> </strong>(express is built over http, so we dont need to import it in express applcns)</p><p>Starting a server without Express:</p><pre>const http = require (&#39;http&#39;);<br>http.createServer( (req, res)=&gt;{<br>  //<br>}).listen(5555);</pre><p>package.json stores details about our project. like libraries used, range of versions of dependencies, desired dependencies, commands etc.</p><p>package-lock.json locks down exact version of each dependency for our project.</p><p>Installing a production dependency: npm install package_name or npm install package_name --save<br>Installing a development dependency (ie dependencies which are not required for production, only for development/debug purposes): npm install package_name --save-dev</p><p>To exclude a file/folder from being pushed to github, we put their path inside .gitignore<br>Example:<br>Contents of .gitignore file</p><pre>/node_modules  // refers to node_modules folder at the rool level // absolute path<br>./node_modules // refers to node_modules folder at the same level of .gitignore // rel path</pre><p>process.argv is an argument vector used to deal with command line inputs.</p><p>First two elems in it are fixed:</p><p>process.argv[0]→ Path where Node.js is installed<br>process.argv[1]→ Path of current file</p><p>fs module</p><pre>const fs = require(&#39;fs&#39;);<br><br>fs.readFile(path, (err, data)=&gt;{}) ;          // Read file<br>fs.writeFile(path, data, (err)=&gt;{}) ;         // Write <br>fs.appendFile(path, data, (err)=&gt;{}) ;        // Add to existing data. Non-destructive<br>fs.rename(path, newpath_or_name, (err)=&gt;{}) ; // Rename or Move <br>fs.unlink(path, (err)=&gt;{}) ;                  // Delete<br>fs.readdir(path, (err, files_arr)=&gt;{});       // To access all file names in a foler: files_arr is an array of file names<br>                                              // can only access folders on the server (or current local project)</pre><p>path module helps to handle Cross-OS path handling and normalization.<br>Example:</p><pre>const path = require(&#39;path&#39;);<br>const filePath = path.join(__dirname, &#39;folder&#39;, &#39;file.txt&#39;);</pre><p>On Windows, filePath would give: C:\your\directory\folder\file.txt</p><p>On Unix (Linux, Mac), filePath would give: /your/directory/folder/file.txt</p><p>It also normalizes path ie. if path contains something like a&gt;b&gt;return_to_a&gt;cthen the path gets converted to a&gt;c .</p><p>Buffer is temporary memory. Raw binary data.</p><p>Some popular asynchronous functions are: setTimeout , setInterval , fs functions without ‘sync’ in their name, database queries like: client.connect() , client.query(..) , collection_name.find() .</p><p>Almost all functions similar to regular functions that we have seen in C++ are synchronous. Examples include, functions on String, Array, fs with ‘sync’ in their name, require , console.log .</p><blockquote><strong>If inside a </strong><strong>Promise object, we call the </strong><strong>resolve function and there are more synchronous lines remaining in the executor function, then they will run to completion, then remaining synchronous codes in the main stack will run and then </strong><strong>.then() handlers are invoked.</strong></blockquote><p>Example:</p><pre>const promise = new Promise((resolve) =&gt; {<br>  console.log(&#39;Synchronous line 1&#39;);<br>  resolve(&#39;Promise resolved&#39;);<br>  console.log(&#39;Synchronous line 2&#39;);<br>});<br><br>promise.then((value) =&gt; {<br>  console.log(&#39;Then handler:&#39;, value);<br>});<br><br>console.log(&#39;Synchronous line 3&#39;);</pre><p>Output:</p><pre>Synchronous line 1<br>Synchronous line 2<br>Synchronous line 3<br>Then handler: Promise resolved</pre><p>Explanation:</p><pre>Synchronous line 1 is logged first.<br>The resolve function is called, marking the promise as resolved.<br>Synchronous line 2 is logged because the <strong>remaining synchronous lines in the executor function complete and then remaining synchronous functions in the main stack before moving to the .then() handlers.<br></strong>Synchronous line 3 is logged.<br><strong>Only after all synchronous code finishes does the .then() handler execute</strong>, logging Then handler: Promise resolved.</pre><p><strong>Note</strong>: Inside a Promise object, only the first resolve or reject function runs, rest all resolve, reject are ignored. Lines written outside any subsequent Resolve or Reject work.</p><h3>How Node.js works:</h3><pre>Call Stack - &gt; Web API  - &gt; Callback Queue<br> |                                  |<br> ^                                  ⌄<br> |  -  -  &lt;  -  -  &lt;  -  -  &lt;  -    |<br><br>Call Stack is essential. Other two are optional.</pre><p><strong>Event loop is only responsile for taking tasks from Callback Queue to Call Stack.</strong></p><p>All remaining tasks are handled by <strong>libuv</strong>.</p><p>Understand this:</p><pre>async function async1(){<br> console.log(&#39;async1 start&#39;);<br> await async2();  // LINE 3<br> console.log(&#39;async1 end&#39;);<br>}<br><br>async function async2(){<br> console.log(&#39;async2 start&#39;);<br>}<br><br>async1();</pre><p>Output:</p><pre>async1 start<br>async2 start<br>async1 end</pre><p>Explanation:</p><pre>1. async1() is called, and it starts executing<br><br>2. console.log(&#39;async1 start&#39;) executes synchronously<br><br>3. The await async2() line pauses async1() execution [ until the Promise that follows the await (i.e. Promise returned by async2 function) is resolved or rejected and <br>all other synchronous tasks in the main stack have been performed ] and calls async2()<br><br>4. Inside async2 we don&#39;t explicitly return a promise, but since its an async function, it has to return a Promise. The final value will be wrapped inside a promise. Since it is returning synchronous stuff so it will immediately resolve the Promise. <br><br>5. The Promise that we were awaiting (in Line 3) has been resolved and remaining code of the async1 function i.e. the line after await is placed into the microtask queue.<br><br>NOTE: After resolution/rejection of a Promise, it is nature of await to schedule the continuation of remaining code after processing of all synchronous code in the main stack first and thus it sends the rem. code to Micro or Macro Task Queue. And since it was a Promise stuff, it went to microtask queue.</pre><blockquote><strong>await sends the remaining code of the corresponding async function in which its present to Micro or Macro Task and they execute after all synchronous tasks have been finished in the main stack and the Promise gets resolved or rejected.</strong></blockquote><p>Every statement/function that we write are actually going inside main() function. So, main() is present at the bottom of the Call Stack.</p><p><strong>Important example to understand order of execution of Asynchronous functions in JS:</strong></p><pre>async function async1() {            // PART A          // Line 1<br>    console.log(&#39;async1 start&#39;);                        // Line 2 <br>    await async2();                                     // Line 3                     <br>    console.log(&#39;async1 end&#39;);                          // Line 4                      <br>}                                                       // Line 5<br>async function async2() {            // PART B          // Line 6<br> console.log(&#39;async2&#39;);                                 // Line 7<br>}                                                       // Line 8<br><br>console.log(&#39;script start&#39;);         // PART C          // Line 10<br><br>setTimeout(function() {              // PART D          // Line 12<br>    console.log(&#39;setTimeout&#39;);<br>}, 0);<br><br>async1();                            // PART E          // Line 16<br><br>new Promise(function(resolve) {      // PART F          // Line 18<br>    console.log(&#39;promise1&#39;);<br>    resolve();<br>}).then(function() {                 // PART G          // Line 21<br>    console.log(&#39;promise2&#39;);<br>});<br><br>console.log(&#39;script end&#39;);           // PART H          // Line 25</pre><p>Output:</p><pre>script start<br>async1 start<br>async2<br>promise1<br>script end<br>async1 end<br>promise2<br>setTimeout</pre><p>Explanation:</p><pre>It is based on the usual order of execution which is:<br>Synchro &gt; Asynchro MicroTasks &gt; Asynchro MacroTasks<br><br>1. Part A, Part B skipped because they have not been called yet<br><br>2. Part C executes. Prints: script start<br><br>3. Part D begins executing. Callback fn of setTimeout or setInterval etc. gets pushed to  Macrotask Queue (1) [asynchroly]<br><br>4. Part E executes, which leads to the execution of Part A<br> Line 2 runs [synchroly] Prints: async1 start<br> Line 3 runs [synchroly] which leads to the execution of Part B<br> And all execution of rem codes in current async fn is paused and sent to MicroTask queue.<br> until the awaited Promise gets resolved/rejected and the main stack is empty of all syncho tasks.<br><br> Line 7 runs [synchroly] Prints: async2<br> async2 function has run all its llines.<br> But since it was defined as an async function it must return a Promise.<br> So, it implictly returns a resolved function<br> The Promise which was awaited at Line3 has been resolved<br> The rem codes of this async fn are pushed to Microtask Queue (1) [asynchroly]<br><br>5. Now from E, me move to Part F, even though we are dealing with Promise creation,<br>things started executing synchroly,<br> Line 19 runs and Prints: promise1 <br> Line 20 runs which denotes that the promise has been resolved<br> Now, the callback fn inside .then() gets pushed to Microtask Queue (2) [asynchroly]<br><br>6. Part H runs, Prints: script end<br><br>- - - - All the synchronous functions have executed now - - - -<br><br>Time for Asynchro Micro ones (in the order they were added in the queue):<br>7. Line 4 runs. Prints: async1 end<br>8. Line 22 runs. Prints: promise2<br><br><br>Time for Asynchro Macro ones:<br>9. Line 13 runs. Prints: setTimeout</pre><h4>To <strong>remove extension from page</strong></h4><p>Either place the file inside the same foldername inside index.html or send any file using sendFile<strong> </strong>from desired path.</p><pre>app.get(&#39;/about&#39;, (req, res)=&gt;{<br>    res.sendFile( __dirname + &#39;/about.html&#39; ); // Better than relative path<br>});</pre><h4><strong>Custom 404 Page</strong></h4><p>To handle requests to undefined llinks</p><p>We add this in bottom of all the paths</p><pre>app.get(&#39;*&#39;, (req, res)=&gt;{<br>    res.sendFile(...);      // send any custom file<br>});</pre><h4>Template Engine</h4><p>Used to make dynamic pages.</p><p>E.g. EJS (Embedded JS), HBS (Handlebars)</p><p>In the project directory, run this on console: npm i ejs to install EJS</p><p>File: server.js</p><pre>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br>app.get(&#39;/profile&#39;, (req, res)=&gt;{<br>    res.render(&#39;profile&#39;); // refers to - - &gt;  /root/views/profile.js <br>});</pre><p>If we want to send some variable to profile.ejs, we can pass an object in second argument of render.<br>File: server.js</p><pre>let user = {<br>    name: &#39;raman kumar&#39;,<br>    email: &#39;ram@proton.me&#39;<br>};<br><br>res.render(&#39;profile&#39;, {user} ); // object sent to profile.ejs file</pre><p>File: profile.ejs</p><pre>&lt;p&gt; Hello Mr &lt;%= user.name %&gt; &lt;/p&gt;</pre><p>In EJS, while giving logic, we use <strong>&lt;% %&gt; </strong><br>and while giving output, we use <strong>&lt;%= %&gt;</strong></p><p>Example:<br>We have passed user object which also contains an array by the name skills</p><pre>&lt;% user.skills.forEach((elem)=&gt;{ %&gt;<br>      &lt;li&gt; &lt;%= elem %&gt; &lt;/li&gt;<br>&lt;% }) %&gt;</pre><p>To import an ejs file to another ejs file, we do:</p><pre>&lt;%- include(&#39;...&#39;); %&gt;</pre><p>-after &lt;% denotes that the file being included should be treated as an HTML file.</p><h3><strong>Middlewares</strong>: <strong>Functions that modifies requests and responses</strong></h3><p>Inside HTTP method handlers like app.get() or app.post()we can pass multiple MWs for a specific path.</p><p>When we use app.<strong>use</strong>((req, res, next)=&gt;{}) , it applies one middleware globally to all req , res</p><p>To use multiple middlewares via app.use(), there are two ways:</p><p>1. Either do like this:</p><pre>app.use(mw1);<br>app.use(mw2);<br>app.use(mw3);</pre><p>2. Pass an array of middlewares</p><pre>app.use([mw1, mw2, mw3]);</pre><p>Example of a middleware which helps us send request forward only when entered age &gt;= 18</p><pre>const reqFilter =  (req, res, next)=&gt;{<br>    if(!req.query.age){ // if age is not passed<br>        res.send(&#39;Please provide age&#39;);<br>    } else if (req.query.age &lt; 18){<br>        res.send(&#39;Age must be &gt;=18&#39;);<br>    }<br>    else{<br>        next(); // forward req, res to next mw if avail.<br>    }<br>};<br><br>app.use(reqFilter); // req, res sent to middleware</pre><h4>Types of middlewares:</h4><p>Application level (applies on all res, req i.e. app.use), Route level, Error handling, Built in, Third party.</p><p>If we want our MW to execute only over specific Route(s), then we use ROUTE Level MWs.</p><p>Example of Route Level MW:</p><pre>app.get(&#39;/about&#39;, reqFilter, (req, res)=&gt;{ // only applying MW to a specified Route<br>      //<br>});</pre><p>We can also place MW in an external file just like we place a function definition in an external file and then we export it.</p><p>To apply MW on a specific group, we can use <strong>Router Object (</strong>i.e. <strong>instance of Router Class)</strong></p><pre>const route = express.Router();   // L1  // Creating instance of Router Class.<br>  /*<br>      // Same as - - - <br><br>      const {Router : Router} = require(&#39;express&#39;);<br>      const route = Router();            // &#39;new&#39; keyword not required<br><br>  */<br>route.get(&#39;/&#39;, (req, res)=&gt;{} );  // L2<br>route.post(&#39;/&#39;, (req, res)=&gt;{} ); // L3<br>app.use(&#39;/a&#39;, route);             // L4<br><br>//   /a/b.html - - &gt; route/b.html<br><br>// GET request to /a get handled by Line 2<br>// POST request to /a get handled by Line 3</pre><h3>MongoDB</h3><p>Mongo Shell mongosh is used to operate with MongoDB using terminal.</p><pre>mongosh<br>test&gt; show databases<br>test&gt; use db1<br>db1&gt; show collections</pre><p>We can also use GUI Compass to use MongoDB.</p><p>Quick comparison of Mongo with SQL:</p><pre>SQL DB   - - &gt; Tables      - - &gt; Rows and Cols<br>Mongo DB - - &gt; Collections - - &gt; Documents (Objects)</pre><p>About MongoDB:</p><p>1. NoSQL database<br>2. Data is stored in collection (collections don’t have row and columns)<br>3. Collection contains object(s), known as Documents.</p><p><strong>Mongo is useful when no of columns in some rows needs to be reduced or extended </strong>i.e. data is not structured. Sometimes cols are being extended sometimes reduced. Helps in scalability.</p><p>Example:</p><p>In SQL:</p><pre>ID  FirstName LastName Age  Nationality<br>1   Ram       Kumar    22   Indian<br>2   Harry     Parker   34   British</pre><p>In MongoDB (Can add or remove columns in individual object):</p><pre>{<br> &quot;_id&quot;: ObjectId(&quot;kasdhfklsaj&quot;),<br> &quot;firstName&quot;: &quot;Ram&quot;,<br> &quot;lastName&quot;: &quot;Kumar&quot;,<br> &quot;age&quot;: 22<br>}, <br>{<br> &quot;_id&quot;: ObjectId(&quot;slkjlskas&quot;);<br> &quot;firstName&quot;: &quot;Shyam&quot;,<br> &quot;lastName&quot;: &quot;Gupta&quot;,<br> &quot;age&quot;: 34,<br> &quot;nationality&quot;: &quot;brit&quot;,<br> &quot;fav_color&quot;: &quot;yellow&quot;<br>}</pre><p>So, Mongo can save memory. In case of SQL, we could have kept addnl rows and provided NULL when vals were not req, but it would have taken more memory.</p><p>mongosh</p><pre>test&gt;  use newdb                           $ creates database newdb but wont be visible unless it has collecn<br>newdb&gt; db.createCollection(&#39;videos&#39;);<br>newdb&gt; show collections                    $ Outputs: videos<br>newdb&gt; db.videos.drop()                    $ Deletes collection &#39;videos&#39; <br>newdb&gt; db.dropDatabase()                   $ Deletes current database</pre><p>CRUD operations from mongosh</p><p>INSERT<strong> </strong>data into a collection:</p><pre>test&gt; use sampledb<br>sampledb&gt; db.createCollection(&#39;products&#39;)<br>sampledb&gt; db.products.insertOne(<br>{ name: &#39;m 40&#39;, brand: &#39;samsung&#39;, price: 250, category: &#39;mobiles&#39; }<br>        )<br>$ NOTE: MongoDB automatically creates id field for us. id field contains an object corresponding to it<br><br>$ .insertOne( { } ), .insertMany( [ { }, { } ] )  ,  .insert( { } );  , .insert( [ { } , { } ] );  // all are valid        </pre><p>READ data from a collection:</p><p>To see all documents inside a collection</p><pre>sampledb&gt; db.products.find()</pre><p><strong>Cursor Object</strong>:<br> A <strong>cursor</strong> is an object in MongoDB that allows us to interact with query results. One document at a time or in batches, rather than loading the entire result set into memory at once.</p><p><strong>Functions that can be applied on Cursor object:</strong></p><p><strong>toArray()</strong>: Converts all documents into a single array.</p><p><strong>forEach()</strong>: Iterates through each document in the cursor.</p><p><strong>next()</strong>: Fetches the next document.</p><p><strong>hasNext()</strong>: Checks if more documents are available.</p><p>UPDATE<strong> </strong>data of a collecn<strong> </strong>(3 objs req)<strong>:</strong></p><pre><strong>sampledb&gt; db.products.updateOne( {name: &quot;lumia 1520&quot;}, {$set: {brand: &quot;microsoft&quot;} } )<br> </strong>                                      |                          |<br>                   Helps us select specific document           Stuffs to edit inside: { $set:  }</pre><p>DELETE<strong> </strong>one document from a collection:</p><pre>sampledb&gt; db.products.deleteOne( {brand: &quot;apple&quot;} )</pre><h3>Node.js with MongoDB</h3><p>READ data:</p><pre>// M U C R<br><br>const {MongoClient} = require (&#39;mongodb&#39;);<br>/* mongodb module exports an obj that contains various properties and methods:<br><br>    {<br>        MongoClient: [class MongoClient],<br>        ObjectId: [class ObjectId],<br>        GridFSBucket: [class GridFSBucket],<br>        // other properties...<br>    }<br><br>    We are accessing value of property MongoClient from the obj<br>    which is MongoClient Class and storing it in a var of same name .<br><br>    We could have used:<br>    const {MongoClient: x} = require(&#39;mongodb&#39;); <br><br>    Which means: Import the value corresponding to MongoClient property<br>    in the object and assign it to variable x.<br><br>    In fact, the line we have used in code is equivalent to:<br>    const {MongoClient: MongoClient} = require(&#39;mongodb);<br>*/<br><br>// Yet another syntax:<br>// Same as - - &gt; const MongoClient = require(&#39;mongodb&#39;).MongoClient<br>// or,     - - &gt; const x = require (&#39;mongodb&#39;).MongoClient<br><br>// Address of MongoDB server. In our case, it is running locally<br>const url = &#39;mongodb://localhost:27017&#39;;//MonDB specific conn protocol       <br><br>// Instance of MongoClient that will connect to the MongoDB server<br>const client = new MongoClient(url);            <br><br>async function getData(){<br>    let result = await client.connect();  <br>    // Connection is initiated. client.connect() returns a promise<br>    // After the promise resolves, result obj is returned<br><br>    // Select specific db<br>    let db = result.db(&#39;sampledb&#39;);             <br><br>    // Select specific collecn<br>    let collection = db.collection(&#39;products&#39;); <br><br>    // Get docs from the current collection in the form of cursor obj<br>    // which is converted to array.<br>    console.log(await collection.find({}).toArray()); <br>    // toArray is asynchro. so we use await.<br>}                                               <br><br>getData();</pre><p>We can keep the connectivity code in a different file:<br>READ data:</p><p>mongodb.js</p><pre>// M U C R<br><br>const  { MongoClient : MongoClient } = require(&#39;mongodb&#39;);<br>const  url = &#39;mongodb://localhost:27017&#39;;<br>const  client = new MongoClient (url);<br><br>async function dbConnect(){<br>    let result = await client.connect();<br>    db = result.db(&#39;sampledb&#39;);<br>    return db.collection(&#39;products&#39;); // fn returns specified collecn<br>}<br><br>module.exports = dbConnect;</pre><p>index.js</p><pre>const dbConnect = require(&#39;./mongodb&#39;);<br>const func = async ()=&gt;{<br>    let data = await dbConnect();   // Req collecn as per mongodb.js   <br>    data = await data.find().toArray();<br>    console.log(data);<br>}<br>func();</pre><p>Note: Functions like find() , insertOne() , insertMany() , updateOne() , client.connect() or dbConnect() they all are <strong>asynchronous</strong> and we add await before them.</p><p>INSERT data</p><p>insert.js</p><pre>const dbConnect = require(&#39;./mongodb.js&#39;);<br>         // . denotes we are dealing with local file<br><br>const insert = async ()=&gt; {<br>    const cln = await dbConnect(); // collecn from ./mongodb.js<br>    const result = await cln.insertOne(  <br>              // insertOne is an async fn.<br>              // We catch the result promise in a variable<br>              // to later know if it ran or not<br>        {name: &#39;lumia 1320&#39;, brand: &#39;nokia&#39;, price: &#39;550&#39;, category: &#39;mobile&#39;}<br>    );<br><br>    if(result.acknowledged){<br>        console.log(&#39;data inserted&#39;);<br>    }<br>}<br><br>insert();</pre><p><strong>NOTE</strong>: While using MongoDB with Node, in functions other than find, like, insert, update, delete (i.e. CUD and not R out of CRUD) there’s a property .acknowledged which can be applied on the result which helps us know if the operation was successful or not. It returns a boolean value.</p><p>Example:</p><pre>let cln = await dbConnect();<br>let x = await cln.updateOne( { }, { $set: {} } );<br>if(x.acknowledged) console.log(&#39;Operation was successful&#39;);</pre><p>To insert multiple data in the collecn:</p><pre>const result = await cln.insertMany(<br>  [ { }, { }, { } ]<br>);</pre><p><strong>NOTE</strong>: .insert()can work for both .insertOne({}) and .insertMany([{}, {}, {}])</p><p>UPDATE data</p><p>mongodb.js file same as above to store connectivity</p><p>update.js file similar to insert.js. Just use updateOne and update in place of insertOne and insertMany</p><p><strong>Note</strong>: If from specified condn in updateOne multiple objects got selected inside one collection, then only the first one will get updated.</p><p><strong>Syntax:<br></strong>Total 3 objects are involved in update</p><pre>.updateOne(    <br>   {condn}, // select specific obj(s) from the cln.<br>            // E.g. {&#39;name&#39;: &#39;lumia 1520&#39;}<br>   {$set: {existing_field1: new_value1, existing_field2: new_value2} }<br>);</pre><p>DELETE Data</p><pre>.deleteOne( {condn} );<br>.deleteMany( {condn} );</pre><p>GET API in Node.js using MongoDB (Read)</p><pre>const express = require (&#39;express&#39;);<br>const dbConnect = require(&#39;./mongodb.js&#39;);<br><br>const app = express();<br><br>// GET API  -  get data from server<br>app.get(&#39;/&#39;, async (req, res)=&gt;{<br>    let cln = await dbConnect();        // cln refers to the collecn<br>    let y = await cln.find().toArray(); // y - all objs in the cln<br>    res.send(y);<br>});<br><br>app.listen(5000, ()=&gt;{<br>    console.log(&#39;Server started at http://localhost:5000&#39;);<br>});</pre><p>POST API in Node.js using MongoDB (Create)</p><p>Send data through Postman and access it using req.body and then apply usual insertOne</p><p>PUT API in Node.js using MongoDB (Update)</p><pre>const express = require(&#39;express&#39;);         // module imported<br>const dbConnect = require(&#39;./mongodb.js&#39;);  // local file imported<br><br>const app = express();<br><br><br>// To handle JSON data that we will send from Postman<br>app.use(express.json());           <br><br>app.put(&#39;/update&#39;, async(req, res)=&gt;{<br>    let cln = await dbConnect();   <br>    let x = await cln.updateOne(<br>        {name: &#39;lumia 730&#39;},   <br>        // we could have used: {name: req.body.name}      <br>        <br>        { $set: req.body }      <br>        // From Postman, we sent this - - &gt; Body - - &gt; raw, JSON - -  &gt; { &quot;price&quot;: &quot;750&quot; }<br>    );<br>    res.send(&#39;Data updated.&#39;);<br>});<br><br>app.listen(5555,()=&gt;{<br>    console.log(&#39;Server started at http://localhost:5555&#39;);<br>});</pre><p>Or, we can use params to make updation cool</p><pre>app.put(&#39;/:model_name&#39;, async(req, res)=&gt;{<br>    let cln = . . . ;<br>    let x = await cln.updateOne(<br>        {name: req.params.model_name},<br>        {$set: req.body}<br>    );<br>}</pre><p>DELETE API in Node.js using MongoDB</p><p>Similar to above code:</p><pre>let cln = await dbConnect();<br>let x = await cln.deleteOne(<br>    req.body; // condn to select a specific obj is sent from postman<br>);</pre><p>Or, we can use params</p><pre>const mongodb = require(&#39;mongodb&#39;);<br>. . .<br>app.delete(&quot;/:id&quot;, async(req, res)=&gt;{<br><br> . . .  <br> cln.deleteOne( { _id: new mongodb.ObjectId(req.params.id) });<br>      . . .<br>} </pre><h3>Mongoose</h3><p>Mongoose is Object Document Mapping for Document based databases. It is not an ORM. ORM is for relational based databases like SQL, Postgres.</p><p>Supports advanced features like Schema, Models, Validation.</p><p><strong>Schema</strong>: Class which specifies which fields can go into database. We create separate Schema for different collection in database. Although we can use one Schema for multiple collections.</p><p><strong>Model</strong>: Class which is used to connect a <strong>collection</strong> of MongoDB <strong>to Node</strong> <strong>over </strong>specified <strong>Schema.</strong></p><p>To insert data into cln, we can create a new instance of ModelName and .save()<br> i.e.</p><pre>let x = new ModelName( { } ) ;<br>await x.save();</pre><p>Or, we can use <strong>await ModelName.create({})</strong> ;</p><p>or, we can use await ModelName.insertMany() ;</p><p><strong>Note</strong>: await ModelName.insert({}); is not valid</p><p>Read, Update, Delete can be directly performed by <strong>await ModelName.find()/.update()/.delete()</strong></p><p>Example:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>// Connecting directly with database<br>mongoose.connect(&#39;mongodb://localhost:27017/sampledb&#39;); <br><br><br>// Defining a Schema which will be used over &#39;products&#39; collection<br>// However, the Schema can be used over other collections also<br>const ProductSchema = mongoose.Schema(   <br>      {<br>            name: String,<br>            price: Number,<br>            brand: String,<br>            category: String<br>      }<br>);<br><br>const ProductModel = mongoose.model(&#39;products&#39;, ProductSchema);<br><br>const main = async()=&gt; {<br>    <br>    // creating instance of Model first before performing insert opn<br>    let data = new ProductModel(<br>                     { name: &#39;xperia 9&#39;,<br>                       price: 2200,<br>                       brand: &#39;sony&#39;,<br>                       category: &#39;mobile&#39;<br>                     }<br>               );<br><br>   <br>    const result = await data.save(); // insert document(obj) in the cln   <br>    console.log(result);<br>}<br><br>main();</pre><p>NOTE: mongoose.Schema() , mongoose.model() are factory functions which doesn’t need the new keyword to create a new instance. It has internal mechanism to handle it. Like in the case of express , we don’t use new keyword.</p><p>Example which contains separate functions for CRUD operations:</p><p>index.js</p><pre><br>const mongoose = require(&#39;mongoose&#39;);<br><br>mongoose.connect(&#39;mongodb://localhost:27017/sampledb&#39;);<br><br>const ProductSchema = mongoose.Schema({<br>    name: String,<br>    price: Number,<br>    brand: String,<br>    category: String<br>});<br><br>const ProductModel = mongoose.model(&#39;products&#39;, ProductSchema);<br><br>// CREATE<br>const saveInDB=async()=&gt;{<br>    let data = new ProductModel({<br>        name: &#39;Xperia 10&#39;,<br>        price: 2500,<br>        brand: &#39;Sony&#39;,<br>        category: &#39;mobile&#39;<br>    });<br><br>    await data.save();<br>}<br><br><br>// READ<br>const findInDB = async()=&gt;{<br>    let data = await ProductModel.find();<br>    console.log(data);<br>}<br><br>// UPDATE<br>const updateInDB = async()=&gt;{<br>    <br>    let data = await ProductModel.updateOne(<br>        {name: &#39;lumia 730&#39;},<br>        {$set: {price: 0}}<br>    );<br><br>    console.log(data);<br>}<br><br><br>// DELETE<br>const deleteInDB = async()=&gt;{<br>    let data = await ProductModel.deleteOne(<br>        {name: &#39;lumia 730&#39;}<br>    );<br>    <br>    console.log(data);<br>}<br><br>findInDB();</pre><p>SEARCH API with multiple fields in Mongoose:</p><pre>app.get(&#39;/search/:key&#39;, async (req, res)=&gt;{<br>    console.log(req.params.key);<br>    let data = await ProductModel.find(<br>        {<br>            &quot;$or&quot;:[<br>                {&quot;name&quot;: {$regex: req.params.key, $options: &#39;i&#39;}},<br>                {&quot;brand&quot;: {$regex: req.params.key}}<br>            ]<br>        }<br>    );<br>    res.send(&#39;search done&#39;);<br>});</pre><p>$options: ‘i’ // Adds case-insensitive feature’</p><p>To upload a file, we can use multer module</p><pre>const express = require(&#39;express&#39;);<br>const multer = require(&#39;multer&#39;);<br><br>const app = express();<br><br>// M S: D: , F: ).s()<br>// We are creating a Middleware<br>const upload = multer({             // multer is taking an object<br>    storage: multer.diskStorage({   // this fn is taking another object which has two functions<br>        destination: function(req, file, cb){<br>            cb(null, &#39;uploads&#39;);<br>        },<br>        filename: function(req, file, cb){<br>            cb(null, file.fieldname+`-`+Date.now()+&#39;.jpg&#39;);<br>        }<br>    })<br>}).single(&quot;user_file&quot;);     // denotes we are only uploading one file<br><br>app.post(&#39;/upload&#39;, upload, (req, res)=&gt;{<br>    res.send(&#39;File uploaded&#39;);<br>});<br><br>app.listen(5000, ()=&gt;{<br>    console.log(&#39;Server started on http://localhost:5000&#39;);<br>});</pre><p>os module:</p><p>Used to get info about current operating system<br>useful for cross os operations.</p><pre><br>os.arch()      // architecture<br>os.freemem()   // free ram in bytes<br>os.totalmem()  // total ram in bytes<br>os.hostname()  // hostname<br>os.platform()  // operating system name<br>os.userInfo()  // info about system</pre><h3>Events</h3><p>In Node.js, everything is event based.</p><p><strong>Events and Event Emitters enable interaction between different parts of an applicn</strong></p><p><strong>Events</strong>: Actions which can be <strong>triggerred</strong> (or say, <strong>emitted</strong>).</p><p><strong>Event Emitters</strong>: Which can trigger events.</p><p>They are <strong>objects of EventEmiter Class</strong>.</p><p>Syntax:</p><pre>const EventEmitter = require(&#39;events&#39;);<br>                                 // importing EventEmitter class<br><br>const x = new EventEmitter();    // x is now an obj of EventEmitter Class<br>                                 // x can now trigger Events<br><br>x.on(&#39;raman&#39;, f1);               // f1 runs when Event `raman` is triggered via x<br><br>x.emit(&#39;raman&#39;);                 // x triggers an Event `raman`</pre><h3>REPL</h3><p>Read Eval Print Loop is a <strong>command line tool </strong>to run JS or Node codes from terminal.</p><p>Type node on terminal and hit enter to enter into REPL mode.</p><p>Type .editor to enter into editor mode.</p><h3>Node.js with MySQL</h3><p>GET API</p><p>File: connect.js</p><pre>const mysql = require(&#39;mysql2&#39;);<br>const conn = mysql.createConnection({<br>    host: &#39;localhost&#39;, <br>    user: &#39;myuser&#39;,<br>    password: &#39;ThisIsMyPassword&#39;,<br>    database: &#39;mytestdb&#39;<br>});<br>module.exports = conn;</pre><p>File: server.js</p><pre>const conn = require(&#39;./connect.js&#39;);<br>app.get(&#39;/&#39;, (res, req)=&gt;{<br> conn.query(`SELECT * `, <br>             function(err, results){<br>                   res.send(results);<br>             });<br>});</pre><p>NOTE: While creating the connection object using mysql2, we cannot change the name of the default keys: i.e. We cannot change <strong>host </strong>to <strong>hostname </strong>for e.g. Keys must be: <strong>host, user, password, database</strong> itself.</p><p>POST API</p><p>inside app.post</p><pre>conn.query(<br>      `INSERT INTO persons(name, age, city) VALUES (?, ?, ?)`, <br>           [name, age, city],<br>           function (err, results) {<br>               //<br>           }<br>);</pre><p>PUT API</p><p>inside app.put</p><pre>conn.query (<br>      `UPDATE table1 SET col1=?, col2=?`,<br>      [val1, val2],<br>      function (err, results) {<br>          //<br>      }<br>);</pre><p>DELETE API</p><p>inside app.delete</p><pre>`DELETE FROM table_name WHERE ... `</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0af44008da0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Notes — 4]]></title>
            <link>https://medium.com/@lrlcwq/javascript-notes-4-5f96d2ce1be7?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f96d2ce1be7</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 12:21:50 GMT</pubDate>
            <atom:updated>2025-01-14T12:21:50.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Notes — 4</h3><h4>Concurrency, Sequential Execution, Promises, delete, .call(), .bind(), NaN, Undefined, null, try, catch, finally</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KV2k087L0IzIHKMzBLYl8A.png" /></figure><p>JS creates the illusion that tasks are being performed parallely, but in reality, at one time, only one stuff is being executed. It is just that the switching between tasks happen very rapidly using <strong>Time Slicing</strong>. This is known as concurrency.</p><p>Concurrency can be handled on single processor but parallelism requires multiple processors. So, <strong>JavaScript supports Concurrency but not Parallelism.</strong></p><p>Example to understand async behaviour of setInterval:</p><pre>function helloSayer(times, name){<br>  let count = 0;<br>  let x = setInterval(()=&gt;{  // When using setInterval, we must take its reference<br>    count ++;<br>    console.log(&#39;Hello &#39; + name);<br>    <br>    if(count==times){<br>      clearInterval(x);<br>    }<br>  }, 100);<br>}<br><br>helloSayer(3, &#39;Arnav&#39;);   // Line A<br>helloSayer(2, &#39;Prateek&#39;); // Line B</pre><p>The complete understanding of the example requires the knowledge of Callstack and MicroTask but for now we can understand the example like this:</p><p>When Line A runs, a countdown of 100s begins (timer1), but in between the control flow doesn’t stop and it reaches to Line B, and a separate countdown of 100ms begins (timer2). The function which was called in Line A has completed the wait of 100ms (timer1) and Hello Arnav gets printed. Then again a countdown of 100ms begins (timer3). Now, timer2 has completed and Hello Prateek gets printed. And a new countdown of 100ms begins (timer4). Now timer3 gets completed and similarly the execution keeps on going.</p><p>Output: <br>Hello Arnav <br>Hello Prateek<br>Hello Arnav <br>Hello Prateek<br>Hello Arnav <br>. . .</p><h4>Sequential Execution in Asynchronous function</h4><p>Understand this before:</p><pre>function f1(callback){<br>    console.log(&#39;This is function 1&#39;);<br>    callback();<br>}<br><br>function f2(){<br>    console.log(&#39;This is function 2&#39;);<br>}<br><br>f1(()=&gt;{<br>    console.log(&#39;This is the body of callback function&#39;)<br>    f2();<br>})<br><br><br>/*<br><br>Outputs:<br><br><br>This is function 1<br>This is the body of callback function<br>This is function 2<br><br>*/</pre><p>Now this:</p><pre>function f1(cb1){<br>    console.log(&#39;function 1&#39;);<br>    setTimeout(()=&gt;{<br>        cb1();<br>    }, 1000);<br>}<br><br>function f2(){<br>    console.log(&#39;function 2&#39;);<br>}<br><br>f1(()=&gt;{<br>    f2();<br>});<br><br>/*<br>Output:<br>function 1 // immediately<br>function 2 // 1 sec after the above line gets printed<br>*/</pre><p><strong>Sequential Execution Using Callbacks:</strong></p><pre>function f1(cb1){<br>    console.log(&#39;f1&#39;);<br>    setTimeout(()=&gt;{<br>        cb1();<br>    }, 1000);<br>}<br><br>function f2(cb2){<br>    console.log(&#39;f2&#39;);<br>    setTimeout(()=&gt;{<br>        cb2();<br>    }, 1000);<br>}<br><br>function f3(){<br>    console.log(&#39;f3&#39;);<br>}<br><br>f1(()=&gt;{        // this block is callback of f1     // cb1<br>    f2(()=&gt;{    // this block is callback of f2     // cb2<br>        f3();<br>    });<br>});<br><br>/*<br><br><br>Output:<br>f1      // immediately<br>f2      // after 1s of above line (ie 1s after start)<br>f3      // after 1s of above line (ie 2s after start)<br><br>*/</pre><p><strong>Sequential Execution Using Promises and .then(), .catch():</strong></p><pre>function f1(){<br>    return new Promise((resolve, reject)=&gt;{<br>        console.log(&#39;f1&#39;);<br>        setTimeout(()=&gt;{<br>            resolve();<br>        }, 1000);<br>    });<br>}<br><br>function f2(){<br>    return new Promise((resolve, reject)=&gt;{<br>        console.log(&#39;f2&#39;);<br>        setTimeout(()=&gt;{<br>            resolve();<br>        }, 1000);<br>    });<br>}<br><br>function f3(){<br>    console.log(&#39;f3&#39;);<br>}<br><br>f1()<br>    .then(()=&gt;{<br>        f2()<br>            .then(()=&gt;{<br>                f3()<br>            })<br>    })<br><br>/*<br><br><br>Output:<br>f1      // immediately<br>f2      // after 1s of above line (ie 1s after start)<br>f3      // after 1s of above line (ie 2s after start)<br><br>*/</pre><p><strong>Sequential Execution Using Promises and async await:</strong></p><pre>function f1(){<br>    return new Promise((resolve, reject)=&gt;{<br>        console.log(&#39;f1&#39;);<br>        setTimeout(()=&gt;{<br>            resolve();<br>        }, 1000);<br>    });<br>}<br><br>function f2(){<br>    return new Promise((resolve, rejct)=&gt;{<br>        console.log(&#39;f2&#39;);<br>        setTimeout(()=&gt;{<br>            resolve();<br>        }, 1000);<br>    });<br>}<br><br>function f3(){<br>    console.log(&#39;f3&#39;);<br>}<br><br>async function func(){<br>    await f1();<br>    await f2();<br>    await f3();<br>}<br><br>func();<br><br>/*<br><br><br>Output:<br>f1      // immediately<br>f2      // after 1s of above line (ie 1s after start)<br>f3      // after 1s of above line (ie 2s after start)<br><br>*/</pre><h4>Promise</h4><p>We can create a Promise object using constructor of default Declared Promise Class which takes only one argument: executor function. The executor function takes two arguments: resolve callback function and reject callback function. The executor function runs as soon as the Promise constructor is called, even if no handlers like .then() or .catch() have been attached.</p><pre>let x = new Promise ( func ); // &#39;func&#39; acts as executor fn<br>                              <br>function func ( resolve , reject ) {<br><br>}</pre><p>Although more popular way is to create executor function at the time of creating Promise itself using Arrow Function. Like this:</p><pre>let x = new Promise ( (resolve, reject) =&gt; {<br>                           //<br>                       }<br>                    );</pre><p>Example to print a given name specified no of times:<br>f1() returns a Promise.</p><pre>function f1(name, times){<br>      return new Promise ((resolve, reject)=&gt;{<br>            let count = 0;<br>            let x = setInterval(()=&gt;{<br>                  count++;<br>                  console.log(&#39;Hello Mr&#39;, name)<br>                  if(count == times){<br>                        clearInterval(x);<br>                        resolve();<br>                }<br>            }, 100);<br>      });<br>}<br><br>f1(&#39;Arnav&#39;, 2);  /*  Outputs:<br>                     Hello Mr Arnav<br>                     Hello Mr Arnav<br>                 */</pre><h4>Extremely Important Note:</h4><p>If we want the stuff written in <em>.then()</em> to run only after the promise has been resolved, we should only have function reference (<strong>ie name of an already defined function, definition of an arrow fn or definition of an anonymously defined fn</strong>) in <em>.then()</em> and this is the basis to achieve sequential execution.</p><p>And if we directly call the function, or write statements, inside <em>.then() </em>then it gets executed immediately without waiting for the associated promise to get resolved or get rejected and the returned stuff is sent to .<em>then(). </em>We can say that this type of execution is <strong>independent</strong> (this is not a technical term).</p><p>Example of sequential (assume f1 as defined in the previous example):</p><pre>f1(&#39;Rama&#39;, 2)<br>      .then(()=&gt;{<br>       console.log(&#39;Running after f1 has resolved&#39;);<br>      });<br>/*<br>      Output:<br>      Hello Mr Rama<br>      Hello Mr Rama<br>      Running after f1 has resolved<br>*/</pre><p>Another example of sequential:<br>Code C-1:</p><pre>f1(&#39;Raman&#39;, 2) // returns a promise, we can apply .then on it or leave it<br> .then(()=&gt;{ // we apply .then<br>  f1(&#39;Sekhar&#39;, 2) // will also return promise <br>                 .then( ()=&gt;{ // .then applied on the promise<br>                       f1(&#39;Gaurav&#39;, 2);  // again promise, but we leave<br>                 } );<br>      });<br>         /*<br>            Outputs:<br>            Hello Mr Raman<br>            Hello Mr Raman<br>            Hello Mr Sekhar<br>            Hello Mr Sekhar<br>            Hello Mr Gaurav<br>            Hello Mr Gaurav  */</pre><p>Notice that this block of code is not sequential:<br>Code C-2:</p><pre>f1(&#39;Raman&#39;, 2)<br> .then( ()=&gt; {<br>  f1 (&#39;Sekhar&#39;, 2);  // line a<br>      } )<br> .then( ()=&gt; {       // line b  .then() is not being applied to the promise of line a<br>       f1 (&#39;Gaurav&#39;, 2);<br>      } )<br>      .then( ()=&gt; {<br>            f1 (&#39;Arnav&#39;, 2);<br>      } )</pre><p>f1 of line a simply stops after executing.</p><p>In Code C-1, we were applying .then inside the block of parent .then. But in Code C-2, that is not the case. So, for that, we will have to use return .</p><p>Corrected code C-2:</p><pre>f1(&#39;Raman&#39;, 2)<br> .then( ()=&gt; {<br>     return f1 (&#39;Sekhar&#39;, 2);<br>  } )<br> .then( ()=&gt; {<br>     return f1 (&#39;Gaurav&#39;, 2);<br>  } )<br>  .then( ()=&gt; {<br>     return f1 (&#39;Arnav&#39;, 2);<br>   } );<br><br>/*<br>Outputs:<br>Hello Raman<br>Hello Raman<br>Hello Sekhar<br>Hello Sekhar<br>Hello Gaurav<br>Hello Gaurav<br>Hello Arnav<br>Hello Arnav<br>*/</pre><p>Good example of independent execution:</p><pre>function f1(name, times){<br>      return new Promise ((resolve, reject)=&gt;{<br>            let count = 0;<br>            let x = setInterval(()=&gt;{<br>                  count++;<br>                  console.log(&#39;Hello Mr&#39;, name)<br>                  if(count == times){<br>                        clearInterval(x);<br>                        resolve();<br>                }<br>            }, 100);<br>      });<br>}<br><br>f1(&#39;Arnav&#39;, 3)<br>    .then( f1(&#39;Prateek&#39;, 2) )<br>    .then( f1(&#39;Rishav&#39;,  2) )</pre><p>We have not passed reference of a function inside .then (like name of an already defined function, or an anoymous function or an arrow function) but have actually called the function which executes the function immediately without waiting for the parent promise to get resolved.<br>And similarly in next .then(), f1 is called immediately.<br>So, none of the promises waits for any other to get resolved first. They all are running immediately.</p><p>Output:</p><pre>Hello Mr Arnav<br>Hello Mr Prateek<br>Hello Mr Rishav<br>Hello Mr Arnav<br>Hello Mr Prateek<br>Hello Mr Rishav<br>Hello Mr Arnav</pre><p>Using async we could have seen similar independent execution, if we would have done:</p><pre>async function task() {<br>      f1(&#39;Arnav&#39;, 3);<br>      f1(&#39;Prateek&#39;, 3);<br>      f1(&#39;Raghav&#39;, 3);<br>}<br><br>task();</pre><p>Output:</p><pre>Hello Mr Arnav<br>Hello Mr Prateek<br>Hello Mr Rishav<br>Hello Mr Arnav<br>Hello Mr Prateek<br>Hello Mr Rishav<br>Hello Mr Arnav</pre><p>If we have a Promise object, we can await that Promise object.</p><p>If a function func1 is returning a promise object, we can add the keyword await before func1 to await the returned object, <strong>which means the code execution will pause until the promise gets resolved or rejected.</strong></p><p><strong>Or, we can say that </strong>await<strong> keyword before a function means, we are applying await on the promise returned by the function.</strong></p><p>await keyword can only be used inside an async function and also never in global scope.</p><pre>function f1(name, times){<br>      return new Promise ((resolve, reject)=&gt;{<br>            let count = 0;<br>            let x = setInterval(()=&gt;{<br>                  count++;<br>                  console.log(&#39;Hello Mr&#39;, name)<br>                  if(count == times){<br>                        clearInterval(x);<br>                        resolve();<br>                }<br>            }, 100);<br>      });<br>}<br><br>async function task() {<br>      await f1(&#39;Arnav&#39;, 3);<br>      await f1(&#39;Prateek&#39;, 3);<br>      await f1(&#39;Raghav&#39;, 3);<br>}<br><br>task();</pre><p>Outputs:</p><pre>Hello Mr Arnav<br>Hello Mr Arnav<br>Hello Mr Arnav<br>Hello Mr Prateek<br>Hello Mr Prateek<br>Hello Mr Prateek<br>Hello Mr Raghav<br>Hello Mr Raghav<br>Hello Mr Raghav</pre><p><strong>Que. </strong>Okay, so, await keyword should only be used inside an async function. But if await is being applied on a function. Should that function be async in nature?</p><p><strong>Ans. </strong>Yes, because await is applied on a promise, and when we do apply await over a function, it means we are applying await over the promise which is being returned by the function. And if a function is returning a promise we should use async keyword.</p><blockquote><strong>In fact,</strong> async<strong> keyword denotes that the function will return a promise.</strong></blockquote><p>We saw that await cannot be used in a global scope. But although, the global scope in JS is synchro, it uses <strong>event loop</strong> to handle asynchro commncn then why not? Well because if we apply await there, the whole JS itself would stop. . . something like that. It can be difficult to deal with it, but modern version of node allows us to use await in global scope.</p><pre>async func f1(){<br>    // . . .<br>}<br>f1();  // async func<br>f2();  // regular func</pre><p>Both the functions run independently of each other.</p><p>Let’s say we have multiple functions and some are in group1 and some in group2.<br>And now we want those two groups of functions to run independently in themselves but sequentially to other.</p><p>For eg, we want the group of (f1, f2, f3) to run independently and when they all have finished, we want the group of (f4, f5, f6) to run independently.</p><p>We can think to use Promise.all like:</p><pre>await Promise.all([f1, f2, f3]);</pre><p>But it’s not ideal because if any one rejects, everything will stop. So, it’s better to use Promise.allSettled( [ ] );</p><pre>await Promise.allSettled( [f1(), f2(), f3()] );<br><br>console.log(&#39;First group completed&#39;);<br><br>await Promise.allSettled( [f4(), f5(), f6()] );</pre><h4>delete keyword</h4><p>delete keyword in JS is used to <strong>delete property of an object </strong>and <strong>not to delete variables which have been defined using </strong>let , const , or var . When we apply delete over those variables, it evaluates to false without returning anything and code execution moves ahead.</p><p><strong>Note</strong>: To access property of an object, we need to provide reference to the parent object.</p><p>Important example:</p><pre>let obj = {<br> a: &#39;wow&#39;,<br> b: &#39;not wow&#39;<br>};<br><br>console.log(a);         // Reference Error<br>console.log(obj.a);     // wow<br><br>console.log(obj);       // { a: &#39;wow&#39;, b: &#39;not wow&#39; }<br><br>delete obj.a;      <br><br>console.log(obj);       // { b: &#39;not wow&#39; }</pre><p>Important example:</p><pre>(function(x){<br>    delete x; // delete on usual variable. evaluates to false. happens nothing. code execn moves ahead.<br>    return x;<br>})(5);<br><br>// Outputs 5</pre><h4>.call( ) and .bind( )</h4><p>.call()<strong> </strong>method is used on a fn while calling it to specify that<strong> </strong>this<strong> </strong>of the fn will refer to which object.</p><p>Syntax:</p><pre>func.call(obj, x, y, z) ;<br>// `this` inside `func` refers to object `obj` and x, y, z.. are arguments</pre><p>Example:</p><pre>let obj1 = {<br> name: &#39;Ram&#39;,<br> age: 21<br>};<br><br>let obj2 = {<br> name: &#39;Keshav&#39;,<br> age: 22<br>};<br><br>function func(x){<br> console.log(`My name is ${this.name} and my age is ${this.age}`);<br> console.log(`My rating on leetcode is ${x}`);<br>}<br><br>func.call(ob1, 1400);<br>func.call(obj2, 1500);</pre><p>Output:</p><pre>My name is Ram and my age is 21<br>My rating on leetcode is 1400<br>My name is Keshav and my age is 22<br>My rating on leetcode is 1500</pre><p><strong>Note</strong>: Since .call() is used on a func while calling it, we can use it with IIFE also.</p><p>Example of IIFE with .call():</p><pre>let obj1 = {name: &#39;Home&#39;, age: 32};<br>(function(){<br> console.log(this.name);<br>}).call(obj1);<br><br>// Outputs: Home</pre><p>.bind() is used to create a new fn from an existing fn and binds it to an object, ie <strong>this</strong> inside the function only refers to that object.</p><p>Example:</p><pre>function func1(){<br>    console.log(`Hello, ${this.name}`);<br>}<br>let obj1 = {name: &#39;Keshav&#39;, age: 22};<br>let obj2 = {name: &#39;Gaurav&#39;, age: 24};<br>let func2 = func1.bind(obj2);<br>func2();<br><br>// Outputs: Hello, Gaurav</pre><p><strong>Note</strong>: If we try to use .bind() method on an arrow function, that doesn’t work. Because, this inside arrow function always refers to the object, inside which it was defined and we can’t change that.</p><p><strong>Comma operator:</strong></p><pre>return func1(), func2(), func3();<br>// func1 runs, then func2, then func3 and only value of func3 is returned.</pre><p>While defining a function, we don’t need to describe how many arguments it will take. We can pass any no of arguments to it, which can be accessed using arguments array.</p><p>Example:</p><pre>function fun(){<br>    console.log(arguments[2]); // Output: cake<br>}<br>fun(&#39;apple&#39;, &#39;banana&#39;, &#39;cake&#39;, &#39;donut&#39;);</pre><h4>NaN, Undefined, null</h4><p>NaN <br>Invalid or Unrepresentable number.<br>Type: Number<br>Examples:</p><pre>0/0<br>Number(&quot;hello&quot;)  <br>&quot;apple&quot; - 5<br>5 * undefined<br>Math.sqrt(-1)<br>NaN + 5<br>NaN - 5<br>NaN * 5<br>NaN / 5</pre><p>Undefined<br>Variable not assigned value yet.<br>Or, stuff returned from a fn of no return type.<br>Type: Undefined<br>Examples:</p><pre>let x; console.log(x); // undefined<br><br>let obj = {a : 10};<br>console.log(obj.b);    // undefined<br><br>let arr = [5, 10, 15];<br>console.log(arr[3]);   // undefined<br><br>function func(){<br>}<br>console.log(func());   // undefined</pre><p>null<br>Special value which can be assigned explicitly to variables to denote that they are empty or that they point nowhere.<br>Type: null<br>Example:</p><pre>let x=null; console.log(x); // null</pre><h4>try, catch, finally</h4><p>A block of code which can produce error, we add that inside <strong><em>try </em></strong>block<br>Whether error occurs due to expected reasons (handled using <strong><em>throw</em></strong>) or unexpected reasons, we handle them in <strong><em>catch</em></strong> block and run different code.<br>The error object in the argument of <em>catch</em> block gets overriden by the error object sent by <em>throw.</em></p><p><strong><em>finally</em></strong> is used to run codes after try, catch have executed.</p><p>Please note that throw or any other error will stop the execution of other lines in the try block immediately, and move the control to catch block.</p><p><strong>Importance of <em>throw</em></strong>: Use it when you know that by default JS would not be able to know the exact reason of the error.</p><p>Example:</p><pre>function loginUser(username, password) {<br>  try {<br>    if (!username || !password) {<br>      throw new Error(&quot;Username and password are required&quot;);<br>    }<br>    console.log(&quot;User logged in successfully&quot;);<br>  } catch (error) {<br>    console.log(&quot;Login failed: &quot; + error.message);<br>  }<br>}<br><br>loginUser(&quot;&quot;, &quot;password123&quot;);<br>// Output: &quot;Login failed: Username and password are required&quot;</pre><p>While resolving a promise, we can also send some parameter for the .then() handler.</p><pre>function func(){<br>      return new Promise((resolve, reject)=&gt;{<br>            resolve(&#39;Rama&#39;);<br>      });<br>}<br><br>func().then(x){<br>            console.log(x);   // Outputs: Rama <br>      }</pre><h4>Some additional notes on Asynchronous operations</h4><p><strong>Note 1:<br></strong> 1. A macrotask runs<br>2. Check if any new microtask has been added. If yes then execute them first.<br>3. Similarly proceed with next macrotasks.</p><p><strong>Note 2:</strong><br><strong>setTimeout()</strong> starts its timer immediately and contents inside it gets added to the macrotask queue, but the key point is that the callback function does not execute until the <strong>specified delay</strong> has passed [condn1] <strong>and</strong> the event loop has finished processing any higher-priority tasks (such as synchronous code and microtasks like Promises) [condn2].</p><p>Example:</p><pre>console.log(&quot;Start timer...&quot;);<br><br>setTimeout(() =&gt; {<br>    console.log(&quot;Timer finished!&quot;);   // Line A<br>    func();                           // Line B<br>}, 2000); // 2 seconds<br><br>console.log(&quot;While waiting for the timer to finish...&quot;);<br>// Line A and Line B will run only when the two conditions stated above will be satisfied.</pre><p><strong>Note 3:</strong><br>Immediately resolved promises:<br>As we know even if an async function returns a plain value, it is still wrapped inside a promise.<br>Whether ther resolution of the promise happen after the remaining synchronous stuff depends on the fact that if the function is returning a synchronous stuff like, regular function calls, returning values, objects etc or an asynchro stuff. If synchro, then the resolution happens immediately and resolution takes place before next synchronous tasks.</p><p>Example:</p><pre>async function x (){<br>    return 5;<br>}<br>console.log(&#39;a&#39;);<br>console.log(x());<br>console.log(&#39;b&#39;);<br><br>/*<br><br>Output: <br>a<br>5  // Immediately resolved promise<br>b <br><br>*/</pre><p>Other example:</p><pre>async function x (){<br>   let y = await client.connect(); // asychro stuff in mongodb<br>                                   // not the complete code. just for understanding <br>   return 5;<br>}<br>console.log(&#39;a&#39;);<br>console.log(x());<br>console.log(&#39;b&#39;):<br><br>/*<br><br>Output: <br>a<br>Promise { &lt;pending&gt; }<br>b<br><br>*/</pre><p><strong>Note 4:<br>Even for an immediately resolved promise</strong>, the behavior of await introduces a scheduling step that ensures the subsequent code after the step of resolution runs asynchronously.</p><p>Or if we are handling promises using .then() , .catch() , we can say that even if a promise is immediately resolved, it does not execute its .then handlers until all the synchronous codes in the call stack finishes executing.</p><p>i.e. the line where a promise is called, that step is synchronous in nature. But, handling of that promise is asynchronous in nature.</p><p>Example:</p><pre>async function async1(){          // 1.<br>    console.log(&#39;async1 start&#39;);  // 2.<br>    await async2();               // 3.<br>    console.log(&#39;async1 end&#39;);    // 4.<br>}<br><br>async function async2(){          // 7.<br>    console.log(&#39;async2&#39;);        // 8.<br>}<br><br>async1();                         // 11.<br>console.log(&#39;hello&#39;);             // 12.<br><br>/*<br><br>Output:<br>async1 start<br>async2<br>hello<br>async1 end<br><br>*/</pre><p>Explanation:</p><p>Line 11 runs. Which triggers the execution of function async1.</p><p>Line 2 runs. [Outputs: async1 start]</p><p>Line 3 runs. It knows it has to await the stuff returned when async2(). async2() will run.</p><p>Line 8 runs. [Outputs: async2] Promise of this block is immediately resolved since there was nothing asynchro.</p><p>Control goes back to Line 3. await sends all the remaining code of the current function to Microtask. Now we cant move forward with the execution of async1 untill all the synchronous tasks (like, line 12) in the main call stack has been finished.</p><p>Line 12 runs. [Outputs: hello]</p><p>Now all the synchronous tasks in the main stack has been finished. We can proceed with the execution of the microtasks (only line 4 is in microtask).</p><p>Line 4 runs. [Outputs: async1 end]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f96d2ce1be7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Notes — 3]]></title>
            <link>https://medium.com/@lrlcwq/javascript-notes-3-b8bdcca95daf?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8bdcca95daf</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 06:40:18 GMT</pubDate>
            <atom:updated>2025-01-14T06:40:50.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Notes — 3</h3><h4>Functions on Promises, IIFEs, setTimeout, setInterval, Pass by Value vs Pass by Reference</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhcjWlsQlyXs3rKhk75oYw.png" /></figure><p>Example of a function taking function in input:</p><pre>function b (y) {<br>    console.log(y);<br>}<br><br>function a (x) {<br>    x(&#39;abc&#39;);<br>}<br><br>a(b);<br><br>// Output: abc</pre><p>We can define the other function at the time of calling of first function also.</p><pre>function func1 (func2) {<br>    func2(&#39;abc&#39;);<br>}<br><br>func1( function f (x) {<br>        console.log(x);<br>    }<br>);<br><br>// Output: abc</pre><p>We can understand it like this that a variable which takes the definition of a function can act as a function.<br>For example: In the below code variable done takes the definition of a function and behaves like that function.</p><pre>function fD (done) {<br> let abc = &quot;This is a sentence&quot; ;<br>      done(abc) ;<br>}<br><br>fD ( function (data) {<br> console.log(data) ;<br>} ) ;<br><br>// Output: This is a sentence</pre><h4>Promises</h4><p>Promises are a way to handle asynchronous communication. Example of a function returning a Promise</p><pre>function fD(correct){<br>    return new Promise ( function (resolve, reject) ) {<br>        let stuff = &quot;some value&quot; ;<br>        // Incomplete code. Code is just for understanding purposes. - - -<br>        if(condn_1){ <br>            resolve (stuff) ;  // .then() will run. We are passing `stuff` also.<br>        } else {<br>            reject ( new Error (&quot;Operation failed&quot;) ) ; // .catch() will run.<br>        }<br>    }) ;<br>}<br><br>// fD() denotes function fD has been called and it will return a Promise object,<br>// upon the returned promise we can apply .then and .catch<br>fD()<br>    .then(function(data){<br>        console.log(data)<br>    })<br>    .catch(function (err) {<br>        console.log(err)<br>    }) ;<br><br>// We could have dealt with .then() or .catch() later on also</pre><p>While creating a Promise in the above example, we could have also used Arrow function, which is a more popular way.</p><pre>// What we did earlier<br>return new Promise ( function (resolve, reject) ) { .. }<br><br>// What we can also do<br>return new Promise ( (resolve, reject) =&gt; { .. } );</pre><p>Note: If promises are linked, .catch() can catch error in any of the linked promises.</p><h4>Functions which can be applied over Promise</h4><p><strong>Promise.all( [ ] )</strong><br>Takes array of promises.<br>Immediately rejects, if any one rejects.<br>Resolves when all are resolved.<br>Example:</p><pre>Promise.all( [p1, p2, p3] )<br> .then( [resp1, resp2, resp3] )<br> .catch((err)=&gt;{}); // As we noted, only one catch is sufficient for multiple chained Promises </pre><p><strong>Promise.allSettled( [ ] )</strong><br>Takes array of promises.<br>Always resolves and returns an array of status of indivial promises.<br>Waits until each promise is settled (either resolved or rejected).<br>Example:</p><pre>Promise.allSettled( [p1, p2, p3] )<br> .then( results =&gt; console.log(results) );<br><br><br>/*<br>Output can be like this:<br>[<br> { status: &#39;fulfilled&#39;, value: &#39;ResponseX&#39; },<br> { status: &#39;rejected&#39;, value: &#39;Error in second request&#39; },<br> { status: &#39;fulfilled&#39;, value: &#39;ResponseY&#39; }<br>]<br>*/</pre><p><strong>Promise.race( [ ] )</strong><br>Takes array of promises.<br>Resolves or rejects as soon as any one promise gets resolved or rej.<br>Example:</p><pre>const p1 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Promise 1 resolved&#39;);<br><br>  }, 1000);<br>});<br><br>const p2 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    reject(&#39;Promise 2 rejected&#39;); <br><br>  }, 500);<br>});<br><br>const p3 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Promise 3 resolved&#39;);<br><br>  }, 1500);<br>});<br><br>Promise.race([p1, p2, p3])<br>  .then((result) =&gt; {<br>    console.log(&#39;Race resolved with:&#39;, result); <br>  })<br>  .catch((error) =&gt; {<br>    console.log(&#39;Race rejected with:&#39;, error); <br>  });<br><br><br>/*<br>Output:<br>Race rejected with: Promise 2 rejected<br><br>Explanation:<br>P2 is fastest. Which is getting rejected. And thus .race gets rejected.<br>*/</pre><p>Another example. p3 is fastest which is getting resolved and thus .race gets resolved.</p><pre>const p1 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Promise 1 resolved&#39;);<br><br>  }, 1000);<br>});<br><br>const p2 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    reject(&#39;Promise 2 rejected&#39;); <br><br>  }, 500);<br>});<br><br>const p3 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Promise 3 resolved&#39;);<br><br>  }, 150);<br>});<br><br>Promise.race([p1, p2, p3])<br>  .then((result) =&gt; {<br>    console.log(&#39;Race resolved with:&#39;, result); <br>  })<br>  .catch((error) =&gt; {<br>    console.log(&#39;Race rejected with:&#39;, error); <br>  });<br>/*<br>Output:<br>Race resolved with: Promise 3 resolved<br>*/</pre><p><strong>Promise.any( [ ] )</strong><br>Takes array of promises.<br>Resolves if any one promise is resolved. Rejects if all promises are rejected.</p><h4>Immediately Inovked Function Expression (IIFE)</h4><p>Syntax: (Define with or without name) (call);</p><p>Examples:</p><p>IIFE taking no input:</p><pre>(function(){<br>  console.log(&#39;green&#39;);<br>})();                              <br><br>// outputs green</pre><p>IIFE taking simple input:</p><pre>(function(a, b){<br>  console.log(a+b);<br>})(5, 6);<br><br>// outputs 11                      </pre><p>IIFE taking function as input (And we know that while passing function as argument, we only give name):</p><pre>function y (a, b){<br>  console.log(a+b);<br>}<br><br>(function(x){<br>  x(5, 10);<br>})(y);                            <br><br>// outputs 15</pre><p>IIFE taking multiple functions as input:</p><pre>(function(a, b){<br>  a(&quot;3^4 is&quot;, b(3, 4));<br>})(console.log, Math.pow);<br><br>// outputs 81  </pre><h4>Nested IIFEs</h4><p>The following code works:</p><pre>(function f1(x){<br>  console.log(x);<br>})(<br>    (function f2(){<br>      return 5;<br>      })()<br>  );<br><br>// outputs 5</pre><p>Note: The above code works. But now understand that why the below code doesn’t work:</p><pre>(function f1(x){<br>  console.log(x);<br>})(       // &lt; - - Line B<br><br>  (function f2(){<br>    return 5;<br>   })();  // &lt; - - Line A<br>  <br>  );    </pre><p>In this code, we have added a semicolon after IIFE f2 has been called. But f2 gets executed before the semicolon itself and the semicolon is treated independently which terminates the opening bracket at Line B prematurely leading to error. So, in cases of nesting of any entities be it IIFEs or Promises, it is advicable to not use semicolons.</p><h4>setTimeout, setInterval</h4><p>setTimeout:<br>Runs once after a given time interval.<br>It takes two parameters:<br>1. function to run<br>2. time after which the function has to run (in milliseconds)</p><p>Syntax:</p><p>Using Anonymous functions:</p><pre>let i = 5;<br>setTimeout( function(){<br>   console.log(i);<br>}, 100); <br><br>// Outputs: 5 </pre><p>Or, using Arrow functions:</p><pre>let i = 5;<br>setTimeout( ()=&gt;{<br>   console.log(i);<br>}, 100);                           <br><br>// Outputs: 5</pre><pre>setTimeout(a, b);  // run func `a` only once after b ms<br>setInterval(a, b); // run func `a` after every b ms</pre><p>To cancel setInterval after sometime, we can pass its reference to clearInterval in setTimeout or we can keep a counter variable.</p><p>Example:</p><pre>function f1 (){<br> console.log(&quot;Hello&quot;);<br>}<br><br>let x = setInterval(f1, 1000);  // run f1 after every 1s<br>setTimeout(f2, 3000);           // run f2 once after 3s which will stop f1 <br><br>function f2(){                  // Due to hoisting, this will go up<br>      clearInterval(x);<br>}<br>/*<br>  Output:<br>  Hello<br>  Hello    <br>*/</pre><h4>Pass by Value vs Pass by Reference</h4><p>JavaScript only supports Pass by value.</p><p><strong>Que.</strong> When we pass an array to a function and make some changes to it, the changes get displayed even outside the function. Doesn’t it makes it pass by reference, like in C++?</p><p><strong>Ans. </strong>No. In case of array, the changes made is also reflected outside, because in case of arrays,<strong> </strong>when we pass an array, we actually pass a pointer which points to the location where the array is stored.<br>So, the pointer is still passed by value, and the changes we make inside a function is performed on the reflected location, which persists everywhere.</p><p>Similar is the case with objects.</p><p>Note: If an <strong>array</strong> or an <strong>object</strong> is declared <strong>constant, </strong>we can still edit<strong> </strong>existing values, add new values (or even sort the array). A constant array or object just means that it defines a constant reference to an array / object. Because of this, we can still change the elements of a ‘constant’ array / object.</p><p><strong>Strings </strong>are <strong>immutable</strong> in JavaScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bdcca95daf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Notes — 2]]></title>
            <link>https://medium.com/@lrlcwq/javascript-notes-2-22ffad43b4c9?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ffad43b4c9</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 14:02:09 GMT</pubDate>
            <atom:updated>2025-01-28T12:39:30.500Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Notes — 2</h3><h4>Closure, this, Equality, Object Inheritance, __proto__, Class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJYbjn5WWmUKhC1wi_G6Qw.png" /></figure><p>In JS, we can also return a function from a function.</p><pre>function outer (param1) {<br> let a1 = 10;<br><br> function inner (param2) {<br>   let a2 = 20;<br>   console.log(param1, a1, param2, a2);  // LINE A<br> }<br>   return inner;<br>}<br><br>let x = outer (&#39;lunch&#39;); // LINE B<br><br>x (&#39;dinner&#39;);            // LINE C</pre><p>Among Line A, B and C, guess what will be the order of execution?<br>The correct order will be: Line B, then C, then A.</p><h4><strong>Closure</strong></h4><p>Scopes available at the birthplace of a function are acquired by the function (infinite nesting supported). But if current scope has a variable and another variable with the same name is defined in child scope, then, the child variable will shadow the outer variable in its own scope. This is known as <strong>shadowing </strong>and it holds true for all: let , const , var.</p><p>Most functional programming languages (like Haskell) support the concept of closure.</p><h4>arguments object</h4><p>arguments<strong> </strong>object can be used to access parameters passed to a function.</p><pre>function hello(){<br> console.log(arguments[0]);<br>}<br>hello(&quot;Message&quot;);<br><br>// Output: Message</pre><pre>function func(){<br>  console.log(arguments[0] + arguments[1] + arguments[2]);<br>}<br>func(5, 10, 15);<br><br>// Output: 30</pre><p>Note: Closure property is not valid for arguments<strong> </strong>object. It means that in a given scope, using argumentsobject, we can only access the parameters which was passed to the current function only, and not of outer functions.</p><h4>this keyword</h4><p>In C++, we can’t use this keyword outside object or inside static methods because those methods do not belong to any object.</p><p>In JavaScript, we can run this without class however.</p><p>In <strong>regular functions</strong> thethis keyword represents the <strong>object that called the function</strong>, which could be the window, the document, a button or whatever. If this is inside a function and the function is inside an object, it will refer to the object.</p><p>With <strong>arrow functions</strong> thethis keyword always represents the <strong>object that defined the arrow function</strong>.</p><p>Regular function:</p><pre>function hello (){<br>      console.log(this);<br>};<br><br>// if window object calls the function: // outputs window <br><br>// if button object calls the function: // outputs button</pre><p>Arrow function:</p><pre>let hello = &quot;&quot;;<br><br>hello = () =&gt; {<br>  console.log(this);<br>}<br><br>// if window object calls the function: // outputs window <br><br>// if button object calls the function: // still outputs window<br><br>                                        // because the arrow func was<br>                                        // defined at windowx</pre><p>Another example:</p><p>Regular function:</p><pre>function func1 (){<br>    console.log(this);<br>};<br><br>let obj1 = {<br>    x : func1<br>};<br><br>obj1.x();<br>// obj1.x is a function, which can be called<br>// this inside regular function - - &gt; refers to object where it was called<br><br>// Code above outputs: { x: [Function: func1] } <br>// which is nothing but obj1</pre><p>Arrow function:</p><pre>let func2 = () =&gt;{<br>    console.log(this);<br>}<br><br>let obj2 = {<br>    y: func2<br>}<br><br>obj2.y(); // Outputs Window, the obj where the arrow func was defined</pre><p>If there was something like obj.b.func() then this inside func would point to object b.</p><h4><strong>Equality in JavaScript</strong></h4><h4>Abstract Equality Comparator ( == )</h4><p>Checks value of data types. If data types are different then typecasting is performed to change the data types to a common data type and then values are checked.</p><p><strong>Note: </strong>Usually in different data types, things get converted to integer or to Primitive in case of Objects.</p><p>Exception to keep in mind:</p><pre>console.log( &#39;5&#39; + 1 ); // expected 6, but outputs 51</pre><p>Because + (plus symbol) is overloaded in javascript to work like this only. Otherwise, string usually gets converted to integer, when working with integers.</p><p>For example:</p><pre>console.log(&#39;5&#39; - 1); // 4<br>console.log(&#39;5&#39; * 2); // 10</pre><p>Examples of Abstract Equality Comparator:</p><pre>0 == &#39;&#39;; // Evaluates to true</pre><p>Explanation of above example: Empty string upon conversion to number gives 0.</p><pre>Number(&#39;&#39;); // This will output 0.</pre><p>Another example:</p><pre>false == &#39;false&#39;;  // Evaluates to false</pre><p>Since the data types are different (boolean and string), Abstract Equality Comparator tries to convert both of them into a common data type.<br>boolean false gets converted to integer 0.<br>Whereas, string &#39;false&#39; getsconverted to NaN<strong><em> </em></strong>(Not a number)<strong><em> </em></strong>because any non-empty string when converted to integer gives NaN.</p><p>Since, 0 is not equal to NaN. Our answer is false.</p><p><strong>Note</strong>: Any whitespace like &#39;&#39; , &#39;\n&#39; , &#39;\t&#39; when converted to number, gives 0. But when comparing them using == , they are treated as <strong>single character string literal</strong> (although &#39;\n&#39; and &#39;\t&#39; are escape sequences) and thus since they get treated as same data types and their values as different. So, the following examples evaluate to false:</p><pre>&#39;&#39; == &#39;\n&#39;;   // false<br>&#39;&#39; == &#39;\t&#39;;   // false<br>&#39;\n&#39; ==&#39;\t&#39;;  // false</pre><p>a==b and b==c , doesn’t implie that a==c in JavaScript. This is <strong>Non Transitive </strong>property.</p><h4>Strict Equality Comparator ( === )</h4><p>Checks for both value and type. No conversion takes place.</p><pre>0=== &#39;&#39;; // Evaluates to false. Since their type is different.</pre><h4>Comparing Arrays</h4><p>In JavaScript, values in Primitive Data Type is Actual Value. Whereas, values in Non-Primitive Data Type is a Pointer which points where the data is.</p><p><strong>Arrays and Objects are Non-Primitive data types.</strong></p><pre>[1,2] == [1,2] // Evaluates to false</pre><p>The above example evaluates to false, because LHS represents an array and RHS represents another array. These two arrays are different. When we perform comparison, the values don’t get compared but the pointers for these two arrays. Since, these are two different arrays, there pointers are different.</p><p>But if we do like:</p><pre>let arr = [1, 2] ;<br>let arr2 = arr ;<br><br>arr2 == arr ; // Evaluates to true because now the pointers are pointing at the same location</pre><p>In fact, whenever arr_a == arr_b , it means we are talking about the same array. Or if obj_a == obj_b , it means we are talking about the same object.</p><h4>Object Inheritance</h4><pre>let obj1 = {<br>    a: 10,<br>    b: 20<br>};<br><br>let obj2 = Object.create(obj1) ; // OBJECT TO OBJECT INHERITANCE<br>                                 // CREATES A NEW EMPTY OBJECT obj2<br>                                 // obj2 IS INHERITING FROM obj1<br><br>obj2 == obj1; // Evaluates to false. Since, these are different objects.</pre><h4>__proto__</h4><p>Points to the original object from which we inherited. __proto__ is only to be used for debugging purposes and never for production code.</p><p>In the above example if we do:</p><pre>obj2.__proto__ == obj1; // Evaluates to true. <br><br>obj2.a ;<br>         // tries to find a in obj2.<br>         // if not found, will try to find in obj2.__proto__ <br>         // if not found, will try to find in obj2.__proto__.__proto__<br>         // goes on, until __proto__ becomes null</pre><p><strong>Note: </strong>Every object has a default __proto__ of its own.</p><p>So if we have obj1 in global scope and we created obj2 inheriting from it.</p><p>obj2.__proto__ is obj1.</p><p>obj2.__proto__.__proto__ is default __proto__ of obj1 , which is not Null.</p><p>obj2.__proto__.__proto__.__proto__ will be null.</p><p>Example to understand how obj2 can access elems of obj1 but don’t have them on its own:</p><pre>let obj1 = {<br>    a: 10,<br>    b: 20<br>} ;<br><br>let obj2 = Object.create(obj1) ; // obj2 inherits from obj1<br>obj2.c = 30 ;<br>obj2.d = 40 ;<br><br>let obj3 = Object.create(obj2) ;  // obj3 inherits from obj2<br><br>// obj1 - - &gt; Object { a : 10 , b : 20 }<br>// obj2 - - &gt; Object { c : 30 , d : 40 }<br>// obj3 - - &gt; Object { }<br>// Even though obj3 is empty. We can access c, d, a, b from it<br><br>console.log(obj3.d) ;  // Output: 40</pre><p>What if obj1 has key a in it and in obj2 we add another key a?</p><p>Will it shadow the a of obj1? Yes it will.</p><p>Example to understand it:</p><pre>// Suppose, obj1 is - - &gt; { a : 10 }<br>// And obj2 is a blank object which inherits from obj1.<br>// obj2 - - &gt; { }<br><br>obj2.a ; // Will output 10 as we understood in the earlier example.<br><br>// But what if we do this?<br>obj2.a ++ ; <br>// It means: obj2.a = obj2.a + 1 ;<br>// So, obj2.a = 10 + 1<br>// Now what happens is that in obj2 &#39;a&#39; gets created. <br>// obj2 - - &gt; { a : 11 }<br>// obj1 - - &gt; { a : 10 }</pre><p>These functions are in window object having global scope which converts any input to the corresponding type:</p><p>String<strong> </strong>,<strong> </strong>Boolean<strong> , </strong>Number<strong> , </strong>Array<strong> , </strong>Object<strong> , </strong>Function.</p><p>For e.g.</p><pre>String(22);          // &#39;22&#39;<br><br>Number(&#39;22&#39;);        // 22<br><br>let f = Function();  // Creates an empty Anonymous function<br>                     // Similar to - - &gt; // let f = function () <br><br>Array(5)             // An array created with 5 empty slots<br>Array(2, 4, 6)       // [2, 4, 6]<br><br>// To create an Array with one numeric value: <br>let x = Array (1) ;<br>x[0] = 5 ;<br><br>// To create an Array with one value which is not numeric, we can create directly<br>Array (true) ;<br>// or,<br>Array (&quot;meow&quot;) ;</pre><p>Note: Look at the below example:</p><pre>let str = String();<br>let obj = Object();<br><br>console.log(str.__proto__.__proto__ == obj.__proto__); // true</pre><p>Other than Object , if we would have used any other function like Number , Boolean , Array , Function , in place of String in the above example, it would still give the same result.</p><p>It means that all those functions inherit from Object.prototype<strong><em> </em></strong>and Object.prototype inherits from Null.</p><p>i.e.<br><strong>All strings created using </strong><strong>String() inherit from </strong><strong>String.prototype<br>All numbers created using </strong><strong>Number() inherit from </strong><strong>Number.prototype<br>All booleans created using </strong><strong>Boolean() inherit from </strong><strong>Boolean.prototype and so on.<br>And </strong><strong>String.prototype , </strong><strong>Number.prototype , </strong><strong>OBoolean.prototype , etc. they all inherit from </strong><strong>Object.prototype</strong></p><p><strong>Que. </strong>String<strong> </strong>,<strong> </strong>Boolean<strong> , </strong>Number<strong> </strong>etc. are functions but we don’t see them contain prototypes. Where are they defined and how were we able to use String.prototype etc.?</p><p><strong>Ans.</strong> All of them are functions. And <strong>all functions are objects</strong>. And object can have key value pairs. And we can add values in objects later on also.</p><p>Example:</p><pre>function func1 () {<br> console.log( &quot;A random function&quot; ) ;<br>}  <br><br>func1.a = &quot;10&quot;; // This is valid</pre><p>Similarly, prototype can be added in String , Number , Boolean etc. later on.</p><p><strong>Note</strong>: Any object which inherits from Function.prototype can be called with parantheses.</p><h4><strong>Important points</strong>:</h4><p>Que. What will be the output of this?</p><pre>typeof Object.create(Boolean.prototype);</pre><p>Ans. We can guess that our answer is something which inherits from Boolean.prototype<strong> </strong>and as we saw earlier, booleans inherit from Boolean.prototype. So, we expect the answer to be boolean. But we get answer: object.</p><p><strong>Learning 1</strong>: If two entities have same .__proto__ it doesn’t mean, that we will get same output when we do typeof on them.</p><p><strong>Learning 2</strong>: Object.create() only creates object.</p><pre>let x = Object.create (Boolean.prototype) ;<br><br><br>x.__proto__ == bool.__proto__ ; // true<br><br><br>typeof x == typeof bool ;       // false</pre><p>Results of typeof are limited: String , Boolean , Number , Object , Function.</p><p>Array also comes in Object.</p><p>If we can reach the scope where a built-in function is defined. We can re-define it.</p><p>Example:</p><pre>let str  = String(222222);<br>let str2 = String(333333);<br><br>console.log(typeof str.charAt(4)) ;  // string<br>console.log(typeof str.charAt) ;     // function<br><br>// Attempting to redefine the default function<br>str.charAt = function ( ) { return &#39;a&#39; ; }  // Doesn&#39;t work<br><br><br>console.log ( str.charAt == str2.charAt ) ; // Gives true<br><br>/*<br><br>It means that str.chatAt and str2.chatAt is pointing to same function.<br>So, function charAt is definitely not present in either str or str2,<br>otherwise any other would not have been able to access it.<br><br>So, we use .__proto__ to find where charAt is defined<br><br>On console we write:<br>str.__proto__.charAt ;           // gives something<br>str.__proto__.__proto__.charAt ; // gives undefined<br><br>It means the function is in str.__proto__, which is String.prototype.<br>Now, we can change the definition:<br><br>*/<br><br>String.prototype.charAt = function () {<br> return &#39; x &#39; ;<br>}<br><br>// The code above works.</pre><p>But the following code doesn’t work. Even though str.__proto__ == String.prototype</p><pre>str.__proto__.charAt = function() {<br>  return &#39;x&#39;;<br>}</pre><p>Explanation: __proto__ sometimes doesn’t work as intended because as we noted earlier, it is only to be used for debugging purposes and never for production code.</p><p>Similarly, default functions of String like slice , splice , replace , substr can be redefined from String.prototype. And Array.prototype or Number.prototype can be used to redefine default functions of Array or Number .</p><p>Example of storing definition of an existing function of Array into a separate variable and redefining it:</p><pre>// Declaring new function joinOriginal and giving it the existing definition of join<br>Array.prototype.joinOriginal = Array.prototype.join; <br><br>// Changing the definition of join<br>Array.prototype.join = function () {<br>  console.log(&#39;Join called on&#39;, this);  <br>  return this.joinOriginal(...arguments);<br>}</pre><p>To release memory being used by a variable, we use delete keyword.</p><pre>window.x = 10 ;<br>console.log (x) ; // 10<br>delete window.x ;<br>console.log (x) ; // undefined</pre><h4>Classes</h4><p>Introduced in ECMA Script 2015 (popularly known as ES 6). It is syntactic sugar : just to aid people coming from C++/Java background. It’s not a new feature. It adds support for new syntax. If classes are removed from language, there would be no effect on the functionalites of the language.</p><p>typeof<strong> </strong>Class<strong> is </strong>function.</p><p>If a is inherited from a function/class:<br>a.__proto__ is equal to (class/fn from where a is defined/inherited)<strong>.prototype</strong></p><p>But if a is inherited from a regular object:<br>a.__proto__ is equal to obj from where a is inherited</p><p>Example:</p><pre>class Person {<br>    constructor (a, b) {<br>        this.name = a ;<br>        this.age  = b ;<br>    }<br>};<br><br>let p = new Person (&#39;John Doe&#39; , 23) ;<br><br>console.log(p.__proto__ == Person.prototype);           // true<br><br>console.log(p.__proto__.__proto__ == Object.prototype); // true</pre><p>When we create a class, a prototype of the class is also created, which inherits from Object.prototype. And the object of the class inherits from that created prototype.</p><p>Inside a class, we can define a function, without using function keyword.<br>Example:</p><pre>class Person {<br>    constructor (name , age) {<br>        this.name = name ;<br>        this.age = age ;<br>    }<br><br>    isAdult () {  // see this<br>        return this.age &gt;= 18 ;<br>    }<br>} ;<br><br>let p1 = new Person ( &#39;kamal&#39; , 27 ) ;<br>console.log (p1.isAdult()) ; // true <br><br>let p2 = new Person ( &#39;meow&#39;, 17 ) ;<br>console.log (p2.isAdult()) ; // false</pre><h4>Inheritance in JS</h4><pre>class Person {<br>    constructor (name , age) {<br>        this.name = name ;<br>        this.age = age ;<br>    }<br><br>    isAdult () {<br>        return this.age &gt;= 18 ;<br>    }<br>} ;<br><br>class Student extends Person {<br>    constructor (name, age, grade){<br>        // Mendatory to call super() in subclass constr and ABOVE `this`<br>        super (name, age) ; <br>        this.grade = grade ;<br>    }<br>} ;<br> <br>let s1 = new Student (&quot;Harry Potter&quot;, 13, 5) ;<br>let s2 = new Student (&quot;Harri Puttar&quot;, 14, 6) ;<br><br>s1.isAdult() ; // Outputs false. </pre><p>It is to be noted that JS doesn’t support Class to Class inheritance. So how did inheritance take place in the above example?<br>The answer is due to the relationship between their prototypes, not because of Class to Class inheritance.</p><pre>s1.__proto__                       // Student.prototype<br>s1.__proto__.__proto__             // Person.prototype<br>s1.__proto__.__proto__.__proto__   // Object.prototype</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ffad43b4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Notes — 1]]></title>
            <link>https://medium.com/@lrlcwq/javascript-notes-1-168f34c2885b?source=rss-2b99a2c5bb7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/168f34c2885b</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sriram]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 06:37:04 GMT</pubDate>
            <atom:updated>2025-01-28T11:57:49.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Notes — 1</h3><h4>Variables, Array, Object, Strings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vtNdIsDZH6s1yftxASQIQ.jpeg" /></figure><p>Notes have been prepared by doing the course of <a href="https://online.codingblocks.com/courses/web-development-online-course">Full Stack Web Development in Node.js by Arnav Gupta, Coding Blocks</a>.<br>Plus, some additional information have been added.</p><p>Attaching external JS file to our html file:</p><pre>&lt;html&gt;<br> &lt;head&gt;<br> &lt;/head&gt;<br> <br> &lt;body&gt;<br>  &lt;!-- content --&gt;<br>  &lt;script src = &#39;./file.js&#39;&gt;<br>  &lt;/script&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Ways to declare a variable</h3><p>x ; let x ; const x ; var x ;</p><p>Variables defined outside function have Global scope (Except in window object, in which variables defined outside are not valid).</p><p>let or const have block scope, i.e. accessible inside current braces and inside all the inner nested braces.<br>Note: Can be re-defined in inner scopes but if in any inner scope, value of outer scope has been used, then redifinition is not possible.</p><p>var has function scope, and not global. Can be re-defined anywhere.</p><blockquote>Example to understand that scope of var is function and not global:</blockquote><pre>function print (){<br>    var x = 10;<br>    console.log(x);<br>}<br>print();         // 10<br>console.log(x);  // error</pre><blockquote>Example to understand how redefining works in block scope i.e. in let and const</blockquote><pre>let/const x = 10;        // Scope A<br><br>function alpha (){       // Scope B<br>    let/const x = 20;    // - - &gt; redefinition possible<br>    if(true){            // Scope C<br>        let x = 30; <br>    }<br>}</pre><p>In Scope B of the above code, if we do not redefine x and directly try to access x it will give 10 (taken from outer Scope A) and now if we try to redefine x it will give error.</p><blockquote>In case of var inside function hoisting takes place for its definition.<br>Try to guess output of the following example:</blockquote><pre>var x = 10;<br>function func(){<br>    console.log(x);<br>    var x = 20;<br>    console.log(x);<br>}<br>func();</pre><p>Output:</p><pre>undefined<br>20</pre><p>Explanation:</p><p>The above code gets converted to:</p><pre>var x = 10;<br>function func(){<br>      var x;<br>      console.log(x);<br>      x = 20;<br>      console.log(x);<br>}<br>func();</pre><p>If we haven’t given in anything at return of a function, its return type is said to be <strong>undefined</strong>.</p><h3>Hoisting</h3><p><strong>Defn of declared functions</strong> and <strong>declared classes </strong>go at the top, before all statements. Thus while writing code, we can give the code of calling a function before its definition. And <em>inside</em> a fn, hoisting takes place for variables defined using var as well, as we saw above.</p><p>These are called<strong> </strong>Declared Functions<strong> </strong>(Hoisted)</p><pre>function func(){<br>    // . . .<br>}</pre><p>These are called Expressed Functions (Not hoisted)</p><pre>var x = function () {<br>    // . . .<br>}</pre><p>Example:</p><pre>func_a(); // this will be valid<br>func_b(); // this wont be<br><br>function func_a(){<br>    // . . .<br>}<br><br>var func_b = function(){<br>    // . . .<br>}</pre><p>As we saw that <em>inside</em> function definition, hoisting doesn’t take place for const and let.<br>But what about outside function, i.e. in global context?<br>How does hoisting take place for them?<br>Turns out that in <em>global context</em>, hoisting for let and const takes place in the <strong>Temporal Dead Zone (TDZ)</strong>. i.e. even though the declarations go at the top, accessing them before initialization will give Reference Error.</p><pre>console.log(x);<br>let x = 50;</pre><p>Behaves like this:</p><pre>let x;          // This is Temporal Dead Zone (TDZ)<br>console.log(x); // Gives Reference Error<br>x=50;</pre><p>The above code is different from:</p><pre>var x;<br>console.log(x); // gives undefined<br>x=50;<br></pre><p>Because, here, x wasn’t declared in TDZ.</p><h3>Arrays</h3><p>Can contain different data types as well.</p><pre>let arr = [&quot;Apple&quot;, &quot;Mango&quot;, &quot;Guava&quot;];<br>console.log ( arr[&quot;length&quot;] ); // 3<br>console.log ( arr.length );    // 3</pre><p>Iterating over elems of array:</p><pre>for(let i=0; i&lt;=2; i++){<br>    console.log( arr[i] );<br>}</pre><h4>Array functions:</h4><pre>let arr = [&quot;Apple&quot;, &quot;Mango&quot;, &quot;Guava&quot;];<br>arr.indexOf(&quot;Mango&quot;);  // 1<br><br>arr.push(&quot;Grapes&quot;);    // add elem to end<br>arr.pop();             // remove elem from end and returns that elem<br><br>arr.shift();           // remove elem from front and returns that elem<br>arr.unshift(&quot;Kiwi&quot;);   // add elem to front<br>arr.reverse();         // reverses the order of elems in the same array</pre><p>Slicing an array is non-destructive: New array is returned and original array is not affected.</p><pre>let arr2 = arr.slice(4);    // arr2 has elems from idx [4, end]<br>let arr2 = arr.slice(4, 6); // arr2 has elems from idx [4, 6) = 4th, 5th </pre><p>S`p`licing is destructive. New array is returned and the original array is affected.</p><pre>let arr2 = arr.splice(4); // arr2 has elems from idx [4, end]<br>                          // arr1 has elems from idx [0, 3]</pre><pre>let arr2 = arr.splice(4, 2);     // The second argument in splice denotes length (like in substr) , to be spliced. So, [4, 6] will be deleted from original array <br><br>arr.splice(4, 3, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;); // Third and beyond argument in splice is used to replace one by one</pre><p>Some other important functions for arrays:</p><pre>let arr2 = arr.concat(&quot;donut&quot;, &quot;eclair&quot;);            // Returns new array by adding new elems to the end. Original array is not affected. Non destructive <br><br>let arr2 = arr.map ( elem =&gt; `&lt;li&gt;elem&lt;/li&gt;`);       // Returns a new arr by modifying each elem of the existing arr. Non destructive<br><br>let str2 = arr.join(&#39;\n&#39;);                           // Joins elems with the given symbl and returns a string<br><br>let str2 = arr.filter( (elem) =&gt; elem.length &gt; 2 );  // Returns a new array, which contains elemenets which pass the given condition</pre><p>On an array, we can apply forEach()<strong> </strong>function. The function itself takes a function in argument (say function2), which is applied over each elem of the array. The function2 in definition takes two parameters, which are <strong>value</strong> and <strong>index</strong> of elems of current array.</p><p>Example:</p><pre>function func(x, y){<br>    console.log(x, y); <br>}<br><br>let arr = [10, 20, 30, 40];<br>arr.forEach(func);</pre><p>Or, using anonymous function to define function at the place of calling itself:</p><pre>let arr = [10, 20, 30, 40];<br>arr.forEach(function(x, y){<br> console.log(x, y);<br>});</pre><p>Or, using arrow function to define function at the place of calling itself:</p><pre>let arr = [10, 20, 30, 40];<br>arr.forEach( (x, y) =&gt; {<br> console.log(x, y);<br>});</pre><p>All the above 3 blocks of code output the same thing:</p><pre>10 0<br>20 1<br>30 2<br>40 3<br></pre><p><strong>for ( of ) </strong><strong>for ( in )</strong></p><pre>for (let x of arr){<br>    // iterates through values in array<br>}<br><br>for (let x in arr){<br>    // iterates through indices in array. Trick: AUfbav Principle<br>    //                                         OF Value, Prop IN<br>}</pre><h3>Objects</h3><p>In JS, we can create objects without class.</p><p><strong>Object = Collection of key-value pairs. </strong>Where key can only be string.</p><pre>let obj = {<br>    a: 100,    // can also write - - &gt; &quot;a&quot; : 100 ,<br>    b: &#39;hello&#39;,<br>    10: 200<br>} ;</pre><p>When the key is given as numeric or any non string like bool. It has different accessing style.</p><pre>obj.a;           // works. // outputs 100<br>obj.10;          // doesnt work<br>obj [&#39; 10 &#39;] ;   // works<br>obj [&#39; a &#39;]  ;   // also works. Similarly, obj [ &#39; true &#39; ] ; // would have worked for bool key</pre><p>Keys can contain values of different data types.</p><pre>var bird = { <br>    x: 100,<br>    y: 20, <br>    color: &quot;blue&quot;, <br>    eggs: [81, 82, 83, 84];<br>};<br><br>bird.color= &quot;red&quot;;<br><br>console.log(bird.x);           // 100<br>console.log(bird.color);       // red<br>console.log(bird.eggs.length); // 4<br><br>bird.eggs.forEach((x, y)=&gt;{    // - - &gt; x: value  y: index<br>    console.log(x, y);<br>});<br><br>/*<br>  Outputs:<br>                81 0<br>                82 1<br>                83 2<br>                84 3<br>*/</pre><p><strong>Note</strong>: Keys can even contain functions or other objects also. <strong>But properties inside object are not local variables.</strong></p><p>Example:</p><pre>var bird= {<br>    x: 10,<br>    y: [20, 30, 40],<br>    z: function(){<br>           console.log(&quot;Generated by a function&quot;);<br>           /*<br>               We can&#39;t access x or y directly.<br>               We will have to use &#39;this&#39; keyword.<br>           */ <br>           // console.log(x);      // Doesn&#39;t work<br>           console.log(this.x);    // Works<br>       }<br>};<br><br>bird.z(); // Outputs: Generated by a function</pre><p>Ways of creating object:</p><ol><li>Object literal</li></ol><pre>var apple = {<br>    taste: &quot;sweet&quot;,<br>    color: &quot;green&quot;,<br>};</pre><p>2. Function declaration (hoisted) | this , new keywords are used.</p><pre>function Fruit(taste, color){<br>    // declaring the properties of object as well as <br>    // assigning values to it<br>    this.taste = taste;   <br>    this.color = color;<br>}<br><br>let mango = new Fruit(&quot;sweet&quot;, &quot;yellow&quot;);<br>let orange = new Fruit(&quot;sour&quot;, &quot;orange&quot;);<br><br>apple;        // {taste: &quot;sweet&quot;, color: &quot;red&quot;}<br>orange.taste; // &quot;sour&quot;</pre><p>3. Function expression (not hoisted) | this , new keywords are used.</p><pre>let f = function (a, b){<br>    this.height = a;<br>    this.weight = b;<br>}<br><br>let a = new f (190, 100);</pre><p><strong>Note</strong>: It’s not possible to create object in JS using arrow functions. Because arrow functions don’t have a this keyword of their own. When we use this inside arrow functions, it refers to the scope where the arrow function was defined.</p><p>4. Class declaration (hoisted) | constructor , this , new keywords are used.</p><pre>class FruitClass{<br>    constructor(taste, color){<br>        this.color = color;<br>        this.taste = taste;<br>    }<br>};<br><br>let kiwi = new FuitClass (&quot;sour&quot;, &quot;green&quot;);</pre><p>5. Class expression (hot hoisted) | constructor , this , new keywords are used.</p><pre>let FruitClass2 = class {<br>    constructor(taste, color){<br>        this.color = color;<br>        this.taste = taste;<br>    }<br>};<br><br>let kiwi2 = new FruitClass2 (&quot;sour&quot;, &quot;dark green&quot;);</pre><h3>Strings</h3><p>There are three ways to create a string: single quotes, double quotes and backticks.</p><pre>let name = &#39;Raghav&#39;;                // Single quotes <br>let newname = `My name is ${name}`; // Backticks can also be used to create String<br>console.log(newname);               // My name is Raghav</pre><p>We can write <strong>long string in single quotes using </strong>\ <br>On output those \ will not be printed and there will be no newline.</p><p>Example:</p><pre>let x = &#39;This is going to be a \<br>very long \<br>string&#39;;<br><br>console.log(x);<br><br>// Output: This is going to be a very long string</pre><p>If inside a quote style, we use another quote style then we need not escape that. But if we use the same quote style inside the given quote style, we will need to escape that.</p><p>Example:</p><pre>let s = &#39; &quot; wow &quot; &#39; ;    // No need to escape double quotes inside single quotes <br>let s = &quot; &#39; wow &#39; &quot; ;    // No need to escape single quotes inside double quotes     <br>let s = &#39; \&#39; wow \&#39; &#39; ;  // Required to escape single quotes inside single quotes<br>let s = &quot; \&quot; wow \&quot; &quot; ;  // Required to escape double quotes inside double quotes<br>let s = ` &quot;wow&quot; ` ;<br>let s = ` &#39;wow&#39; ` ;</pre><p>To output newline in strings defined using single and double quotes:</p><pre>let s = &quot; string in \n multiple \n lines &quot; ;</pre><p>To provide newline when using backtick :</p><pre>let s = ` string in<br> multiple<br> lines ` ;</pre><p>It gets printed exactly as it has been written. Thats why backticks are called string literals.</p><pre>let name = &quot;Raghav&quot; ;<br>let a = &quot;My name is &quot; + name ; // concatenation in double quotes // same for single quotes <br>let b = `My name is ${name}` ; // concatenation in backticks<br><br>// ${ } , can also have mathematical operations<br>let c = ` So, 10 plus 2 is : ${ 10 + 2 } ` ;</pre><h4><strong>String functions:</strong></h4><pre>let x = &quot;Raghav is Raghav&quot;; <br>x.length ;             // 16<br>x.indexOf(&#39;ghav&#39;);     // First occurence - - &gt; 2<br>x.indexOf(&#39;ghav&#39;, 4);  // Start searching from index 4 // - - &gt; 12<br>x.lastIndexOf(&#39;ghav&#39;); // Last occurrence - - &gt; 12<br>x.slice(2, 3);         // [ 2, 3 )<br><br>// splice is not suppported on string<br><br>x.substring(2, 3);     // [2, 3)<br><br>x.slice(-6, -4);       // [-6, -4) // Last char is denoted as -1<br>                       // But, x.slice(5, 3); or, x.slice(-4, -6);  both dont work. We can&#39;t slice in reverse direction <br>                       // i.e. we can only slice from less value to larger value<br><br>x.substr(3, 4);        // second param is length // starting from index 3. length 4. // [3, 6]<br>x.substr(-6, 4);       // [-6, including -6 idx till 4 elements to the right] <br>x.split(&quot;&lt;delim&gt;&quot;);    // Returns a new array of substrings separated by given delimitter<br>                       // Non destructive</pre><pre>let x = &quot;Hi-how-are-you&quot;;<br>let y= x.split(&#39;-&#39;);<br>console.log(y);<br>// Outputs: [ &#39;Hi&#39;, &#39;how&#39;, &#39;are&#39;, &#39;you&#39; ]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168f34c2885b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>