<?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 perfectogo on Medium]]></title>
        <description><![CDATA[Stories by perfectogo on Medium]]></description>
        <link>https://medium.com/@jasurbek.go.dev?source=rss-d12b6a49500d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2VKUcWXmVGh13ulj</url>
            <title>Stories by perfectogo on Medium</title>
            <link>https://medium.com/@jasurbek.go.dev?source=rss-d12b6a49500d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:10:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasurbek.go.dev/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[JS — PROMISING]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-promising-6e48ceeb53f5?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e48ceeb53f5</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 10:12:02 GMT</pubDate>
            <atom:updated>2023-08-22T10:12:02.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — PROMISING</h3><h3>Introduction</h3><p>In web development, asynchronous programming is notorious for being a challenging topic.</p><p>An <em>asynchronous operation</em> is one that allows the computer to “move on” to other tasks while waiting for the asynchronous operation to complete. Asynchronous programming means that time-consuming operations don’t have to bring everything else in our programs to a halt.</p><p>There are countless examples of asynchronicity in our everyday lives. Cleaning our house, for example, involves asynchronous operations such as a dishwasher washing our dishes or a washing machine washing our clothes. While we wait on the completion of those operations, we’re free to do other chores.</p><p>Similarly, web development makes use of asynchronous operations. Operations like making a network request or querying a database can be time-consuming, but JavaScript allows us to execute other tasks while awaiting their completion.</p><h3>What is a Promise?</h3><p>Promises are <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> that represent the eventual outcome of an asynchronous operation. A <a href="https://www.codecademy.com/resources/docs/javascript/promise">Promise</a> object can be in one of three states:</p><ul><li><strong>Pending</strong>: The initial state — the operation has not completed yet.</li><li><strong>Fulfilled</strong>: The operation has completed successfully and the promise now has a <em>resolved value</em>. For example, a request’s promise might resolve with a <a href="https://www.codecademy.com/resources/docs/javascript/json">JSON</a> object as its value.</li><li><strong>Rejected</strong>: The operation has failed and the promise has a reason for the failure. This reason is usually an Error of some kind.</li></ul><p>We refer to a promise as <em>settled</em> if it is no longer pending — it is either fulfilled or rejected. Let’s think of a dishwasher as having the states of a promise:</p><ul><li><strong>Pending</strong>: The dishwasher is running but has not completed the washing cycle.</li><li><strong>Fulfilled</strong>: The dishwasher has completed the washing cycle and is full of clean dishes.</li><li><strong>Rejected</strong>: The dishwasher encountered a problem (it didn’t receive soap!) and returns unclean dishes.</li></ul><p>If our dishwashing promise is fulfilled, we’ll be able to perform related tasks, such as unloading the clean dishes from the dishwasher. If it’s rejected, we can take alternate steps, such as running it again with soap or washing the dishes by hand.</p><p>All promises eventually settle, enabling us to write logic for what to do if the promise fulfills or if it rejects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_EhftEKeF8lmvNkyNm-XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syhnqKRdFxdG8bh61dI8Lg.png" /></figure><h3>Constructing a Promise Object</h3><p>Let’s construct a promise! To create a new <a href="https://www.codecademy.com/resources/docs/javascript/promise">Promise</a> object, we use the new keyword and the Promise constructor method:</p><pre>const executorFunction = (resolve, reject) =&gt; { };<br>const myFirstPromise = new Promise(executorFunction);</pre><p>The Promise constructor method takes a function parameter called the <em>executor function</em> which runs automatically when the constructor is called. The executor function generally starts an asynchronous operation and dictates how the promise should be settled.</p><p>The executor function has two function parameters, usually referred to as the resolve() and reject() <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a>. The resolve() and reject() functions aren’t defined by the programmer. When the Promise constructor runs, JavaScript will pass <strong>its own</strong> resolve() and reject() functions into the executor function.</p><ul><li>resolve is a function with one argument. Under the hood, if invoked, resolve() will change the promise’s status from pending to fulfilled, and the promise’s resolved value will be set to the argument passed into resolve().</li><li>reject is a function that takes a reason or error as an argument. Under the hood, if invoked, reject() will change the promise’s status from pending to rejected, and the promise’s rejection reason will be set to the argument passed into reject().</li></ul><p>Let’s look at an example executor function in a Promise constructor:</p><pre>const executorFunction = (resolve, reject) =&gt; {<br> if (someCondition) {<br>     resolve(&#39;I resolved!&#39;);<br> } else {<br>     reject(&#39;I rejected!&#39;); <br> }<br>}<br>const myFirstPromise = new Promise(executorFunction);</pre><p>Let’s break down what’s happening above:</p><ul><li>We declare a variable myFirstPromise</li><li>myFirstPromise is constructed using new Promise() which is the Promise constructor method.</li><li>executorFunction() is passed to the constructor and has two functions as parameters: resolve and reject.</li><li>If someCondition evaluates to true, we invoke resolve() with the string &#39;I resolved!&#39;</li><li>If not, we invoke reject() with the string &#39;I rejected!&#39;</li></ul><p>In our example, myFirstPromise resolves or rejects based on a simple condition, but, in practice, promises settle based on the results of asynchronous operations. For example, a database request may fulfill with the data from a query or reject with an error thrown. In this exercise, we’ll construct promises which resolve synchronously to more easily understand how they work.</p><h3>The Node setTimeout() Function</h3><p>Knowing how to construct a <a href="https://www.codecademy.com/resources/docs/javascript/promise">promise</a> is useful, but most of the time, knowing how to <em>consume</em>, or use, promises will be key. Rather than constructing promises, you’ll be handling Promise <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> returned to you as the result of an asynchronous operation. These promises will start off pending but settle eventually.</p><p>Moving forward, we’ll be simulating this by providing you with <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> that return promises which settle after some time. To accomplish this, we’ll be using <a href="https://www.codecademy.com/resources/docs/javascript/window/setTimeout">setTimeout()</a>. setTimeout() is a Node API (a comparable API is provided by web browsers) that uses callback functions to schedule tasks to be performed after a delay. setTimeout() has two parameters: a callback function and a delay in milliseconds.</p><pre>const delayedHello = () =&gt; {<br>  console.log(&#39;Hi! This is an asynchronous greeting!&#39;);<br>};<br><br>setTimeout(delayedHello, 2000);</pre><p>Here, we invoke setTimeout() with the callback function delayedHello() and 2000. In at least two seconds delayedHello() will be invoked. But why is it “at least” two seconds and not exactly two seconds?</p><p>This delay is performed asynchronously — the rest of our program won’t stop executing during the delay. Asynchronous JavaScript uses something called <em>the event-loop</em>. After two seconds, delayedHello() is added to a line of code waiting to be run. Before it can run, any synchronous code from the program will run. Next, any code in front of it in the line will run. This means it might be more than two seconds before delayedHello() is actually executed.</p><p>Let’s look at how we’ll be using setTimeout() to construct asynchronous promises:</p><pre>const returnPromiseFunction = () =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(( ) =&gt; {resolve(&#39;I resolved!&#39;)}, 1000);<br>  });<br>};<br><br>const prom = returnPromiseFunction();</pre><p>In the example code, we invoked returnPromiseFunction() which returned a promise. We assigned that promise to the variable prom. Similar to the asynchronous promises you may encounter in production, prom will initially have a status of pending.</p><p>Let’s explore setTimeout() a bit more.</p><h3>Consuming Promises</h3><p>The initial state of an asynchronous promise is pending, but we have a guarantee that it will settle. How do we tell the computer what should happen then? Promise <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> come with an aptly named <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> method. It allows us to say, “I have a promise, when it settles, <strong>then</strong> here’s what I want to happen…”</p><p>In the case of our dishwasher promise, the dishwasher will run <strong>then</strong>:</p><ul><li>If our promise rejects, this means we have dirty dishes, and we’ll add soap and run the dishwasher again.</li><li>If our promise fulfills, this means we have clean dishes, and we’ll put the dishes away.</li></ul><p>.then() is a higher-order function— it takes two callback <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> as arguments. We refer to these <a href="https://www.codecademy.com/resources/docs/javascript/callbacks">callbacks</a> as <em>handlers</em>. When the promise settles, the appropriate handler will be invoked with that settled value.</p><ul><li>The first handler, sometimes called onFulfilled, is a <em>success handler</em>, and it should contain the logic for the promise resolving.</li><li>The second handler, sometimes called onRejected, is a <em>failure handler</em>, and it should contain the logic for the promise rejecting.</li></ul><p>We can invoke .then() with one, both, or neither handler! This allows for flexibility, but it can also make for tricky debugging. If the appropriate handler is not provided, instead of throwing an error, .then() will just return a promise with the same settled value as the promise it was called on. One important feature of .then() is that it always returns a promise. We’ll return to this in more detail in a later exercise and explore why it’s so important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtC4dObSz3DErWk2vsx0Ow.png" /></figure><h3>Success and Failure Callback Functions</h3><p>To handle a “successful” promise, or a promise that resolved, we invoke <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> on the promise, passing in a success handler callback function:</p><pre>const prom = new Promise((resolve, reject) =&gt; {<br>  resolve(&#39;Yay!&#39;);<br>});<br><br>const handleSuccess = (resolvedValue) =&gt; {<br>  console.log(resolvedValue);<br>};<br><br>prom.then(handleSuccess); // Prints: &#39;Yay!&#39;</pre><p>Let’s break down what’s happening in the example code:</p><ul><li>prom is a promise which will resolve to &#39;Yay!&#39;.</li><li>We define a function, handleSuccess(), which prints the argument passed to it.</li><li>We invoke prom‘s .then() function passing in our handleSuccess() function.</li><li>Since prom resolves, handleSuccess() is invoked with prom‘s resolved value, &#39;Yay&#39;, so &#39;Yay&#39; is logged to the console.</li></ul><p>With typical promise consumption, we won’t know whether a promise will resolve or reject, so we’ll need to provide the logic for either case. We can pass both a success callback and a failure callback to .then().</p><pre>let prom = new Promise((resolve, reject) =&gt; {<br>  let num = Math.random();<br>  if (num &lt; .5 ){<br>    resolve(&#39;Yay!&#39;);<br>  } else {<br>    reject(&#39;Ohhh noooo!&#39;);<br>  }<br>});<br><br>const handleSuccess = (resolvedValue) =&gt; {<br>  console.log(resolvedValue);<br>};<br><br>const handleFailure = (rejectionReason) =&gt; {<br>  console.log(rejectionReason);<br>};<br><br>prom.then(handleSuccess, handleFailure);</pre><p>Let’s break down what’s happening in the example code:</p><ul><li>prom is a promise which will randomly either resolve with &#39;Yay!&#39; or reject with &#39;Ohhh noooo!&#39;.</li><li>We pass two handler <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> to .then(). The first will be invoked with &#39;Yay!&#39; if the promise resolves, and the second will be invoked with &#39;Ohhh noooo!&#39; if the promise rejects.</li></ul><blockquote>Note: The success callback is sometimes called the “success handler function” or the onFulfilled function. The failure callback is sometimes called the “failure handler function” or the onRejected function.</blockquote><h3>Using catch() with Promises</h3><p>One way to write cleaner code is to follow a principle called <em>separation of concerns</em>. Separation of concerns means organizing code into distinct sections each handling a specific task. It enables us to quickly navigate our code and know where to look if something isn’t working.</p><p>Remember, <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> will return a promise with the same settled value as the promise it was called on if no appropriate handler was provided. This implementation allows us to separate our resolved logic from our rejected logic. Instead of passing both handlers into one .then(), we can chain a second .then() with a failure handler to a first .then() with a success handler and both cases will be handled.</p><pre>prom<br> .then((resolvedValue) =&gt; {<br>   console.log(resolvedValue);<br> })<br> .then(null, (rejectionReason) =&gt; {<br>   console.log(rejectionReason);<br> });</pre><p>Since JavaScript doesn’t mind whitespace, we follow a common convention of putting each part of this chain on a new line to make it easier to read. To create even more readable code, we can use a different promise function: <a href="https://www.codecademy.com/resources/docs/javascript/promise/catch">.catch()</a>.</p><p>The .catch() function takes only one argument, onRejected. In the case of a rejected promise, this failure handler will be invoked with the reason for rejection. Using .catch() accomplishes the same thing as using a .then() with only a failure handler.</p><p>Let’s look at an example using .catch():</p><pre>prom<br> .then((resolvedValue) =&gt; {<br>   console.log(resolvedValue);<br> })<br> .catch((rejectionReason) =&gt; {<br>   console.log(rejectionReason);<br> });</pre><p>Let’s break down what’s happening in the example code:</p><ul><li>prom is a promise which randomly either resolves with &#39;Yay!&#39; or rejects with &#39;Ohhh noooo!&#39;.</li><li>We pass a success handler to .then() and a failure handler to .catch().</li><li>If the promise resolves, .then()‘s success handler will be invoked with &#39;Yay!&#39;.</li><li>If the promise rejects, .then() will return a promise with the same rejection reason as the original promise and .catch()‘s failure handler will be invoked with that rejection reason.</li></ul><p>Let’s practice writing .catch() <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a>.</p><h3>Chaining Multiple Promises</h3><p>One common pattern we’ll see with asynchronous programming is multiple operations which depend on each other to execute or that must be executed in a certain order. We might make one request to a database and use the data returned to us to make another request and so on! Let’s illustrate this with another cleaning example, washing clothes:</p><p>We take our dirty clothes and put them in the washing machine. If the clothes are cleaned, <strong>then</strong> we’ll want to put them in the dryer. After the dryer runs, if the clothes are dry, <strong>then</strong> we can fold them and put them away.</p><p>This process of chaining promises together is called <em>composition</em>. Promises are designed with composition in mind! Here’s a simple promise chain in code:</p><pre>firstPromiseFunction()<br>.then((firstResolveVal) =&gt; {<br>  return secondPromiseFunction(firstResolveVal);<br>})<br>.then((secondResolveVal) =&gt; {<br>  console.log(secondResolveVal);<br>});</pre><p>Let’s break down what’s happening in the example:</p><ul><li>We invoke a function firstPromiseFunction() which returns a promise.</li><li>We invoke <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> with an anonymous function as the success handler.</li><li>Inside the success handler we <strong>return</strong> a new promise — the result of invoking a second function, secondPromiseFunction() with the first promise’s resolved value.</li><li>We invoke a second .then() to handle the logic for the second promise settling.</li><li>Inside that .then(), we have a success handler which will log the second promise’s resolved value to the console.</li></ul><p>In order for our chain to work properly, we had to return the promise secondPromiseFunction(firstResolveVal). This ensured that the return value of the first .then() was our second promise rather than the default return of a new promise with the same settled value as the initial.</p><p>Let’s write some promise chains!</p><h3>Avoiding Common Mistakes</h3><p>Promise composition allows for much more readable code than the nested callback syntax that preceded it. However, it can still be easy to make mistakes. In this exercise, we’ll go over two common mistakes with promise composition.</p><p><strong>Mistake 1:</strong> Nesting promises instead of chaining them.</p><pre>returnsFirstPromise()<br>.then((firstResolveVal) =&gt; {<br>  return returnsSecondValue(firstResolveVal)<br>    .then((secondResolveVal) =&gt; {<br>      console.log(secondResolveVal);<br>    })<br>})</pre><p>Let’s break down what’s happening in the above code:</p><ul><li>We invoke returnsFirstPromise() which returns a promise.</li><li>We invoke <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> with a success handler.</li><li>Inside the success handler, we invoke returnsSecondValue() with firstResolveVal which will return a new promise.</li><li>We invoke a second .then() to handle the logic for the second promise settling all <strong>inside</strong> the first then()!</li><li>Inside that second .then(), we have a success handler which will log the second promise’s resolved value to the console.</li></ul><p>Instead of having a clean chain of promises, we’ve nested the logic for one inside the logic of the other. Imagine if we were handling five or ten promises!</p><p><strong>Mistake 2:</strong> Forgetting to return a promise.</p><pre>returnsFirstPromise()<br>.then((firstResolveVal) =&gt; {<br>  returnsSecondValue(firstResolveVal)<br>})<br>.then((someVal) =&gt; {<br>  console.log(someVal);<br>})</pre><p>Let’s break down what’s happening in the example:</p><ul><li>We invoke returnsFirstPromise() which returns a promise.</li><li>We invoke .then() with a success handler.</li><li>Inside the success handler, we create our second promise, but we forget to return it!</li><li>We invoke a second .then(). It’s supposed to handle the logic for the second promise, but since we didn’t return, this .then() is invoked on a promise with the same settled value as the original promise!</li></ul><h3>Using Promise.all()</h3><p>When done correctly, promise composition is a great way to handle situations where asynchronous operations depend on each other or execution order matters. What if we’re dealing with multiple promises, but we don’t care about the order? Let’s think in terms of cleaning again.</p><p>For us to consider our house clean, we need our clothes to dry, our trash bins emptied, and the dishwasher to run. We need <strong>all</strong> of these tasks to complete but not in any particular order. Furthermore, since they’re all getting done asynchronously, they should really all be happening at the same time!</p><p>To maximize efficiency we should use <em>concurrency</em>, multiple asynchronous operations happening together. With promises, we can do this with the function Promise.all().</p><p>Promise.all() accepts an array of promises as its argument and returns a single promise. That single promise will settle in one of two ways:</p><ul><li>If every promise in the argument array resolves, the single promise returned from Promise.all() will resolve with an array containing the resolve value from each promise in the argument array.</li><li>If any promise from the argument array rejects, the single promise returned from Promise.all() will immediately reject with the reason that promise rejected. This behavior is sometimes referred to as <em>failing fast</em>.</li></ul><p>Let’s look at a code example:</p><pre>let myPromises = Promise.all([returnsPromOne(), returnsPromTwo(), returnsPromThree()]);<br><br>myPromises<br>  .then((arrayOfValues) =&gt; {<br>    console.log(arrayOfValues);<br>  })<br>  .catch((rejectionReason) =&gt; {<br>    console.log(rejectionReason);<br>  });</pre><p>Let’s break down what’s happening:</p><ul><li>We declare myPromises assigned to invoking Promise.all().</li><li>We invoke Promise.all() with an array of three promises— the returned values from <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a>.</li><li>We invoke <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> with a success handler which will print the array of resolved values if each promise resolves successfully.</li><li>We invoke <a href="https://www.codecademy.com/resources/docs/javascript/promise/catch">.catch()</a> with a failure handler which will print the first rejection message if any promise rejects.</li></ul><h3>Review</h3><p>Awesome job! Promises are a difficult concept even for experienced developers, so pat yourself on the back. You’ve learned a ton about asynchronous JavaScript and promises. Let’s review:</p><ul><li>Promises are JavaScript <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> that represent the eventual result of an asynchronous operation.</li><li>Promises can be in one of three states: pending, resolved, or rejected.</li><li>A promise is settled if it is either resolved or rejected.</li><li>We construct a promise by using the new keyword and passing an executor function to the Promise constructor method.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/window/setTimeout">setTimeout()</a> is a Node function which delays the execution of a callback function using the event-loop.</li><li>We use <a href="https://www.codecademy.com/resources/docs/javascript/promise/then">.then()</a> with a success handler callback containing the logic for what should happen if a promise resolves.</li><li>We use <a href="https://www.codecademy.com/resources/docs/javascript/promise/catch">.catch()</a> with a failure handler callback containing the logic for what should happen if a promise rejects.</li><li>Promise composition enables us to write complex, asynchronous code that’s still readable. We do this by chaining multiple .then()‘s and .catch()‘s.</li><li>To use promise composition correctly, we have to remember to return promises constructed within a .then().</li><li>We should chain multiple promises rather than nesting them.</li><li>To take advantage of concurrency, we can use Promise.all().</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e48ceeb53f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Modules in Node]]></title>
            <link>https://medium.com/@jasurbek.go.dev/implementing-modules-in-node-acfa8184477e?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/acfa8184477e</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 07:06:37 GMT</pubDate>
            <atom:updated>2023-08-22T07:06:37.122Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Article on modular programs and implementing modules in the Node runtime environment.</strong></p><h3>What are Modules?</h3><p><em>Modules</em> are reusable pieces of code in a file that can be exported and then imported for use in another file. A <em>modular</em> program is one whose components can be separated, used individually, and recombined to create a complex system.</p><p>Consider the diagram below of an imaginary program written in a file <strong>my_app.js</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*uVBBcMnXUg7jF9fBgaPz_A.png" /></figure><blockquote>Note: The words “module” and “file” are often used interchangably</blockquote><p>Instead of having the entire program written within <strong>my_app.js</strong>, its components are broken up into separate modules that each handle a particular task. For example, the <strong>database_logic.js</strong> module may contain code for storing and retrieving data from a database. Meanwhile, the <strong>date_formatting.js</strong> module may contain functions designed to easily convert date values from one format to another (a common headache among programmers!).</p><p>This modular strategy is sometimes called <em>separation of concerns</em> and is useful for several reasons. What do you think those reasons might be?</p><p>Write down a few of your ideas before revealing the reasons below:</p><p>By isolating code into separate files, called modules, you can:</p><ul><li>find, fix, and debug code more easily.</li><li>reuse and recycle defined logic in different parts of your application.</li><li>keep information private and protected from other modules.</li><li>prevent pollution of the global namespace and potential naming collisions, by cautiously selecting variables and behavior we load into a program.</li></ul><p>Implementing modules in your program requires a small bit of management. In the remainder of this article, we will be covering:</p><ul><li>How to use the Node.js <strong>module.exports</strong> object to <em>export</em> code from a file - meaning its functions and/or data can be used by other files/modules.</li><li>How to use the Node.js <strong>require()</strong> function to <em>import</em> functions and/or data from another module.</li></ul><h3>Implementations of Modules in JavaScript: Node.js vs ES6</h3><p>Before we dive in, it should be noted that there are multiple ways of implementing modules depending on the <em>runtime environment</em> in which your code is executed. In JavaScript, there are two runtime environments and each has a preferred module implementation:</p><ol><li>The <a href="https://nodejs.org/en/about/">Node</a> runtime environment and the <strong>module.exports</strong> and <strong>require()</strong> syntax.</li><li>The browser’s runtime environment and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">ES6</a> <strong>import</strong>/<strong>export</strong> syntax.</li></ol><p>This article will focus on using the <strong>module.exports</strong> and <strong>require()</strong> syntax in the Node runtime environment. For more information, you can read the two articles linked below</p><ul><li><a href="https://www.codecademy.com/courses/learn-intermediate-javascript/articles/implementing-modules-using-es-6-syntax">Implementing modules using ES6 Syntax</a></li><li><a href="https://www.codecademy.com/articles/introduction-to-javascript-runtime-environments">Introduction to JavaScript Runtime Environments</a></li></ul><h3>Implementing Modules in Node</h3><p>Every JavaScript file that runs in a Node environment is treated as a distinct module. The functions and data defined within each module can be used by any other module, as long as those resources are properly <em>exported</em> and <em>imported</em>.</p><p>Suppose you wanted to write a simple program that would display the freezing point and boiling point of water in Fahrenheit. However, you only know the values in Celsius to be 0 (freezing) and 100 (boiling). Luckily you happen to know how to convert Celsius to Fahrenheit!</p><p>Such a program might look like this:</p><pre>/* water-limits.js */<br>function celsiusToFahrenheit(celsius) {<br>  return celsius * (9/5) + 32;<br>}<br><br>const freezingPointC = 0;<br>const boilingPointC = 100;<br><br>const freezingPointF = celsiusToFahrenheit(freezingPointC);<br>const boilingPointF = celsiusToFahrenheit(boilingPointC);<br><br>console.log(`The freezing point of water in Fahrenheit is ${freezingPointF}`);<br>console.log(`The boiling point of water in Fahrenheit is ${boilingPointF}`);</pre><p>This <strong>water-limits.js</strong> program is simple but let’s break it down into its parts:</p><ul><li>At the top of the file, the function <strong>celsiusToFahrenheit()</strong> is declared. When given a value in Celsius, it will return the value converted to Fahrenheit. Both input and output will be a number.</li><li>Below, <strong>freezingPointC</strong> and <strong>boilingPointC</strong> are assigned the known values <strong>0</strong> and <strong>100</strong>, respectively.</li><li>Using these values and the function <strong>celsiusToFahrenheit()</strong>, the additional values <strong>freezingPointF</strong> and <strong>boilingPointF</strong> are calculated.</li><li>Lastly, these values are printed to the console.</li></ul><p>Executing this file using Node would look something like this:</p><pre>$ node water-limits.js<br>The freezing point of water in Fahrenheit is 32<br>The boiling point of water in Fahrenheit is 212</pre><p>Now, you decide to write a second program. In this program, the user can input any temperature value in Celsius and the program responds by printing the input temperature converted to Fahrenheit.</p><p>For example, you might want to be able to run such a program and see a response like so:</p><pre>$ node celsius-to-fahrenheit.js 100<br>100 degrees Celsius = 212 degrees Fahrenheit</pre><p>The JavaScript below would do just that:</p><pre>/* celsius-to-fahrenheit.js */<br>function celsiusToFahrenheit(celsius) {<br>    return celsius * (9/5) + 32;<br>}<br><br>const celsiusInput = process.argv[2]; // Get the 3rd input from the argument list<br>const fahrenheitValue = celsiusToFahrenheit(celsiusInput);<br><br>console.log(`${celsiusInput} degrees Celsius = ${fahrenheitValue} degrees Fahrenheit`);</pre><p>Now, let’s break down the <strong>celsius-to-fahrenheit.js</strong> program:</p><ul><li>At the top of the file, the function <strong>celsiusToFahrenheit()</strong> is declared. When given a value in Celsius, it will return the value converted to Fahrenheit. Both input and output will be a number.</li><li>On the next line of code, <strong>celsiusInput</strong> is assigned <strong>process.argv[2]</strong>. When a program is executed in the Node environment, <strong>process.argv</strong> is an array holding the arguments provided. In this case, it looks like <strong>[&#39;node&#39;, &#39;celsius-to-fahrenheit.js&#39;, &#39;100&#39;]</strong>. So, <strong>process.argv[2]</strong> returns <strong>100</strong>.</li><li>Using this value and the function <strong>celsiusToFahrenheit()</strong>, the additional value <strong>fahrenheitValue</strong> is calculated.</li><li>Lastly, a message is printed to the console displaying this data.</li></ul><p>Notice anything similar between the two programs, <strong>water-limits.js</strong> and <strong>celsius-to-fahrenheit.js</strong>? Both programs implement the function <strong>celsiusToFahrenheit()</strong>! Not only did we write this function twice, but if we ever need to make changes to the function we’ll also have to make those changes in two places.</p><p>Creating a module that exports a <strong>celsiusToFahrenheit()</strong> function that can be used by both of these programs would solve this repetitive code problem.</p><h3>module.exports</h3><p>To create a module, you simply have to create a new file where the functions can be declared. Then, to make these functions available to other files, add them as properties to the built-in <strong>module.exports</strong> object:</p><pre>/* converters.js */<br>function celsiusToFahrenheit(celsius) {<br>  return celsius * (9/5) + 32;<br>}<br><br>module.exports.celsiusToFahrenheit = celsiusToFahrenheit;<br><br>module.exports.fahrenheitToCelsius = function(fahrenheit) {<br>  return (fahrenheit - 32) * (5/9);<br>};</pre><p>The code snippet above demonstrates two ways of exporting functions from a module. Let’s break it down:</p><ul><li>At the top of the new file, <strong>converters.js</strong>, the function <strong>celsiusToFahrenheit()</strong> is declared.</li><li>On the next line of code, the first approach for exporting a function from a module is shown. In this case, the already-defined function <strong>celsiusToFahrenheit()</strong> is assigned to <strong>module.exports.celsiusToFahrenheit</strong>.</li><li>Below, an alternative approach for exporting a function from a module is shown. In this second case, a new function expression is declared and assigned to <strong>module.exports.fahrenheitToCelsius</strong>. This new method is designed to convert Fahrenheit values back to Celsius.</li><li>Both approaches successfully store a function within the <strong>module.exports</strong> object.</li></ul><p><strong>module.exports</strong> is an object that is built-in to the Node.js runtime environment. Other files can now import this object, and make use of these two functions, with another feature that is built-in to the Node.js runtime environment: the <strong>require()</strong> function.</p><h3>require()</h3><p>The <strong>require()</strong> function accepts a string as an argument. That string provides the <a href="https://www.freecodecamp.org/news/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8/">file path</a> to the module you would like to import.</p><p>Let’s update <strong>water-limits.js</strong> such that it uses <strong>require()</strong> to import the <strong>.celsiusToFahrenheit()</strong> method from the <strong>module.exports</strong> object within <strong>converters.js</strong>:</p><pre>/* water-limits.js */<br>const converters = require(&#39;./converters.js&#39;);<br><br>const freezingPointC = 0;<br>const boilingPointC = 100;<br>const freezingPointF = converters.celsiusToFahrenheit(freezingPointC);<br>const boilingPointF = converters.celsiusToFahrenheit(boilingPointC);<br><br>console.log(`The freezing point of water in Fahrenheit is ${freezingPointF}`);<br>console.log(`The boiling point of water in Fahrenheit is ${boilingPointF}`);</pre><p>In this case, <strong>./</strong> is a relative path indicating that <strong>converters.js</strong> is stored in the same folder as <strong>water-limits.js</strong>. When you use <strong>require()</strong>, the entire <strong>module.exports</strong> object is returned and stored in the variable <strong>converters</strong>. This means that both the <strong>.celsiusToFahrenheit()</strong> and <strong>.fahrenheitToCelsius()</strong> methods can be used in this program!</p><h3>Using Object Destructuring to be more Selective With require()</h3><p>In many cases, modules will export a large number of functions but only one or two of them are needed. You can use object destructuring to extract only the needed functions.</p><p>Let’s update <strong>celsius-to-fahrenheit.js</strong> and only extract the <strong>.celsiusToFahrenheit()</strong> method, leaving <strong>.fahrenheitToCelsius()</strong> behind:</p><pre>/* celsius-to-fahrenheit.js */<br>const { celsiusToFahrenheit } = require(&#39;./converters.js&#39;);<br><br>const celsiusInput = process.argv[2]; <br>const fahrenheitValue = celsiusToFahrenheit(celsiusInput);<br><br>console.log(`${celsiusInput} degrees Celsius = ${fahrenheitValue} degrees Fahrenheit`);</pre><p>With this approach, the remainder of the program works the same way but the program avoids importing a function it does not need.Implementations of Modules in JavaScript: Node.js vs ES6</p><p>Before we dive in, it should be noted that there are multiple ways of implementing modules depending on the <em>runtime environment</em> in which your code is executed. In JavaScript, there are two runtime environments and each has a preferred module implementation:</p><ol><li>The <a href="https://nodejs.org/en/about/">Node</a> runtime environment and the <strong>module.exports</strong> and <strong>require()</strong> syntax.</li><li>The browser’s runtime environment and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">ES6</a> <strong>import</strong>/<strong>export</strong> syntax.</li></ol><p>This article will focus on using the <strong>module.exports</strong> and <strong>require()</strong> syntax in the Node runtime environment. For more information, you can read the two articles linked below</p><ul><li><a href="https://www.codecademy.com/courses/learn-intermediate-javascript/articles/implementing-modules-using-es-6-syntax">Implementing modules using ES6 Syntax</a></li><li><a href="https://www.codecademy.com/articles/introduction-to-javascript-runtime-environments">Introduction to JavaScript Runtime Environments</a></li></ul><h3>Review</h3><p>In this article, you have learned the following:</p><ul><li>The benefits of implementing modular programs.</li><li>How to use the Node.js <strong>module.exports</strong> object to <em>export</em> code from a file - meaning its functions and/or data can be used by other files/modules.</li><li>How to use the Node.js <strong>require()</strong> function to <em>import</em> the functions and/or data from another module.</li><li>How to use object destructuring to only import the desired components of a module.</li></ul><p>Congratulations on reaching this milestone! With a little more practice, you will soon be able to handle Node.js modules with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acfa8184477e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — RUNTIME ENV]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-runtime-env-a6d5c9bd3898?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6d5c9bd3898</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 06:52:12 GMT</pubDate>
            <atom:updated>2023-08-22T06:52:12.793Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — RUNTIME ENV</h3><h3>Introduction to JavaScript Runtime Environments</h3><p>An introduction to the Node runtime environment and a browser’s runtime environment.</p><h3>What is a Runtime Environment?</h3><p>A <em>runtime environment</em> is where your program will be executed. It determines what global objects your program can access and it can also impact how it runs. This article covers the two JavaScript runtime environments:</p><ol><li>the runtime environment of a browser (like <a href="https://www.google.com/chrome/">Chrome</a>, or <a href="https://www.mozilla.org/en-US/firefox/">Firefox</a>)</li><li>the Node runtime environment</li></ol><h3>A Browser’s Runtime Environment</h3><p>The most common place where JavaScript code is executed is in a browser. For example, using any <a href="https://www.codecademy.com/articles/visual-studio-code">text editor</a>, you could create a file on your own computer called <strong>my_website.html</strong> and put the following HTML code inside:</p><pre>&lt;!-- my_website.html --&gt;<br>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt; My Website &lt;/h1&gt;<br>    &lt;script&gt; window.alert(&#39;Hello World&#39;); &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Save your file, then open your favorite browser. Most browsers will allow you to load websites that you have created locally by going to the menu File &gt; Open File &gt; <strong>my_website.html</strong>.</p><p>Upon loading, the embedded <strong>&lt;script&gt;&lt;/script&gt;</strong> will execute and the <strong>window.alert()</strong> method will create a pop-up box in your browser with the text <strong>&quot;Hello World&quot;</strong>. How is this possible? Where did the <strong>window.alert()</strong> method come from and how can it control your browser?</p><p>The answer is that you are executing this code in the <em>browser’s runtime environment</em>. The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/alert"><strong>window.alert()</strong></a> method is built into this environment and any program executed in a browser has access to this method. In fact, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window"><strong>window</strong></a> object provides access to a huge amount of data and functionality relating to the open browser window beyond just <strong>.alert()</strong>.</p><blockquote>Try replacing <strong>window.alert()</strong> with <strong>window.prompt()</strong> or <strong>window.confirm()</strong></blockquote><p>Applications created for and executed in the browser are known as <em>front-end</em> applications. For a long time, JavaScript code could only be executed in a browser and was used exclusively for creating front-end applications. In order to create <em>back-end</em> applications that could run on a computer WITHOUT a browser, you would need to use other programming languages such as Java or PHP.</p><h3>The Node Runtime Environment</h3><p>In 2009, the <em>Node runtime environment</em> was created for the purpose of executing JavaScript code without a browser, thus enabling programmers to create <em>full-stack</em> (front-end and back-end) applications using only the JavaScript language.</p><p>Node is an entirely different runtime environment, meaning that browser-environment data values and functions, like <strong>window.alert()</strong>, can’t be used. Instead, the Node runtime environment gives back-end applications access to a variety of features unavailable in a browser, such as access to the server’s file system, database, and network.</p><p>For example, suppose you created a file called <strong>my-app.js</strong>. We can check to see the directory that this file is located in using the Node runtime environment variable <strong>process</strong>:</p><pre>// my-app.js<br>console.log(process.env.PWD);</pre><blockquote>Notice that we are using <strong>console.log</strong> now instead of <strong>window.alert()</strong> since the <strong>window</strong> object isn’t available</blockquote><p><strong>process</strong> is an object containing data relating to the JavaScript file being executed. <strong>process.env</strong> is an object containing environment variables such as <strong>process.env.PWD</strong> which contains the current working directory (and stands for “<strong>P</strong>rint <strong>W</strong>orking <strong>D</strong>irectory”).</p><p>To execute the JavaScript code in this file, first make sure that you have <a href="https://www.codecademy.com/articles/setting-up-node-locally">set up Node on your computer</a>. Then, open up a <a href="https://www.codecademy.com/learn/learn-the-command-line">terminal</a> and run the following command:</p><pre>$ node my-app.js<br>/path/to/working/directory</pre><p>The <strong>node</strong> command tells your computer to execute the <strong>my-app.js</strong> file in the Node environment. You can also use the <strong>node</strong> command without a file argument to open up the Node <strong>R</strong>ead-<strong>E</strong>val-<strong>P</strong>rint-<strong>L</strong>oop (REPL):</p><pre>$ node<br>&gt; process.env.HOME<br>&#39;/home/ccuser&#39;</pre><h3>Summary</h3><p>A <em>runtime environment</em> is where your program will be executed. JavaScript code may be executed in one of two runtime environments:</p><ol><li>a browser’s runtime environment</li><li>the Node runtime environment</li></ol><p>In each of these environments, different data values and functions are available, and these differences help distinguish front-end applications from back-end applications.</p><ul><li>Front-end JavaScript applications are executed in a browser’s runtime environment and have access to the <strong>window</strong> object.</li><li>Back-end JavaScript applications are executed in the Node runtime environment and have access to the file system, databases, and networks attached to the server.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6d5c9bd3898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — CLASSES]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-classes-e6fbf07a00c5?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6fbf07a00c5</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 06:29:42 GMT</pubDate>
            <atom:updated>2023-08-22T06:29:42.404Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>JS — CLASSES</strong></h3><h3>Introduction to Classes</h3><p>JavaScript is an <em>object-oriented programming</em> (OOP) language we can use to model real-world items. In this lesson, you will learn how to make <em>classes</em>. Classes are a tool that developers use to quickly produce similar <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>.</p><p>Take, for example, an object representing a dog named halley. This dog’s name (a key) is &quot;Halley&quot; (a value) and has a behavior (another key) of 0 (another value). We create the halley object below:</p><pre>let halley = {<br>  _name: &#39;Halley&#39;,<br>  _behavior: 0,<br>  <br>  get name() {<br>    return this._name;<br>  },<br>  <br>  get behavior() {<br>    return this._behavior;<br>  },<br>    <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>Now, imagine you own a dog daycare and want to create a catalog of all the dogs who belong to the daycare. Instead of using the syntax above for every dog that joins the daycare, we can create a Dog class that serves as a template for creating new Dog objects. For each new dog, you can provide a value for their name.</p><p>As you can see, classes are a great way to reduce duplicate code and debugging time.</p><p>After we lay the foundation for classes in the first few exercises, we will introduce inheritance and static <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> — two features that will make your code more efficient and meaningful.</p><h3>Constructor</h3><p>In the last exercise, you created a class called Dog, and used it to produce a Dog object.</p><p>Although you may see similarities between class and object syntax, there is one important method that <a href="https://www.codecademy.com/resources/docs/javascript/sets">sets</a> them apart. It’s called the <em>constructor</em> method. JavaScript calls the constructor() method every time it creates a new <em>instance</em> of a class.</p><pre>class Dog {<br>  constructor(name) {<br>    this.name = name;<br>    this.behavior = 0;<br>  }<br>}</pre><ul><li>Dog is the name of our class. By convention, we capitalize and PascalCase class names.</li><li>JavaScript will invoke the constructor() method every time we create a new instance of our Dog class.</li><li>This constructor() method accepts one argument, name.</li><li>Inside of the constructor() method, we use the <a href="https://www.codecademy.com/resources/docs/javascript/this">this</a> keyword. In the context of a class, this refers to an instance of that class. In the Dog class, we use this to set the value of the Dog instance’s name property to the name argument.</li><li>Under this.name, we create a property called behavior, which will keep track of the number of times a dog misbehaves. The behavior property is always initialized to zero.</li></ul><p>In the next exercise, you will learn how to create Dog instances.</p><h3>Instance</h3><p>Now, we’re ready to create class instances. An <em>instance</em> is an object that contains the property names and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> of a class, but with unique property values. Let’s look at our Dog class example.</p><pre>class Dog {<br>  constructor(name) {<br>    this.name = name;<br>    this.behavior = 0;<br>  } <br>}<br><br>const halley = new Dog(&#39;Halley&#39;); // Create new Dog instance<br>console.log(halley.name); // Log the name value saved to halley<br>// Output: &#39;Halley&#39;</pre><p>Below our Dog class, we use the new keyword to create an instance of our Dog class. Let’s consider the line of code step-by-step.</p><ul><li>We create a new variable named halley that will store an instance of our Dog class.</li><li>We use the new keyword to generate a new instance of the Dog class. The new keyword calls the constructor(), runs the code inside of it, and then returns the new instance.</li><li>We pass the &#39;Halley&#39; string to the Dog constructor, which <a href="https://www.codecademy.com/resources/docs/javascript/sets">sets</a> the name property to &#39;Halley&#39;.</li><li>Finally, we log the value saved to the name key in our halley object, which logs &#39;Halley&#39; to the console.</li></ul><p>Now you know how to create instances. In the next exercise, you will learn how to add getters, setters, and methods.</p><h3>Methods</h3><p>At this point, we have a Dog class that spins up <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> with name and behavior properties. Below, we will add getters and a method to bring our class to life.</p><p>Class method and getter syntax is the same as it is for objects <strong>except you can not include commas between methods</strong>.</p><pre>class Dog {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }<br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>In the example above, we add getter <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> for name and behavior. Notice, we also prepended our property names with underscores (_name and _behavior), which indicate these properties should not be accessed directly. Under the getters, we add a method named .incrementBehavior(). When you call .incrementBehavior() on a Dog instance, it adds 1 to the _behavior property. Between each of our methods, we did <em>not</em> include commas.</p><h3>Method Calls</h3><p>Finally, let’s use our new <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> to access and manipulate data from Dog instances.</p><pre>class Dog {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }   <br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}<br><br>const halley = new Dog(&#39;Halley&#39;);</pre><p>In the example above, we create the Dog class, then create an instance, and save it to a variable named halley.</p><p>The syntax for calling methods and getters on an instance is the same as calling them on an object — append the instance with a period, then the property or method name. For methods, you must also include opening and closing parentheses.</p><p>Let’s take a moment to create two Dog instances and call our .incrementBehavior() method on one of them.</p><pre>let nikko = new Dog(&#39;Nikko&#39;); // Create dog named Nikko<br>nikko.incrementBehavior(); // Add 1 to nikko instance&#39;s behavior<br>let bradford = new Dog(&#39;Bradford&#39;); // Create dog name Bradford<br>console.log(nikko.behavior); // Logs 1 to the console<br>console.log(bradford.behavior); // Logs 0 to the console</pre><p>In the example above, we create two new Dog instances, nikko and bradford. Because we increment the behavior of our nikko instance, but not bradford, accessing nikko.behavior returns 1 and accessing bradford.behavior returns 0.</p><h3>Inheritance I</h3><p>Imagine our doggy daycare is so successful that we decide to expand the business and open a kitty daycare. Before the daycare opens, we need to create a Cat class so we can quickly generate Cat instances. We know that the properties in our Cat class (name, behavior) are similar to the properties in our Dog class, though, there will be some differences, because of course, cats are not dogs.</p><p>Let’s say that our Cat class looks like this:</p><pre>class Cat {<br>  constructor(name, usesLitter) {<br>    this._name = name;<br>    this._usesLitter = usesLitter;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br> <br>  get usesLitter() {<br>    return this._usesLitter;<br>  }<br><br> get behavior() {<br>    return this._behavior;<br>  }  <br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>In the example above, we create a Cat class. It shares a couple of properties (_name and _behavior) and a method (.incrementBehavior()) with the Dog class from earlier exercises. The Cat class also contains one additional property (_usesLitter), that holds a boolean value to indicate whether a cat can use their litter box.</p><p>When multiple classes share properties or <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>, they become candidates for <em>inheritance</em> — a tool developers use to decrease the amount of code they need to write.</p><p>With inheritance, you can create a <em>parent</em> class (also known as a superclass) with properties and methods that multiple <em>child</em> classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.</p><p>Let’s abstract the shared properties and methods from our Cat and Dog classes into a parent class called Animal.</p><pre>class Animal {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }   <br>    <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>In the example above, the Animal class contains the properties and methods that the Cat and Dog classes share (name, behavior, .incrementBehavior()).</p><p>The diagram to the right shows the relationships we want to create between the Animal, Cat, and Dog classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcPEvHUcOQ0CyTucO0zQmA.png" /></figure><h3>Inheritance II</h3><p>In the last exercise, we created a parent class named Animal for two child classes named Cat and Dog.</p><p>The Animal class below contains the shared properties and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> of Cat and Dog.</p><pre>class Animal {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }   <br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>The code below shows the Cat class that will inherit information from the Animal class.</p><pre>class Cat {<br>  constructor(name, usesLitter) {<br>    this._name = name;<br>    this._usesLitter = usesLitter;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }<br>  <br>  get usesLitter() {<br>    return this._usesLitter;<br>  }<br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>To the right, in <strong>main.js</strong>, you will put what you learned to practice by creating a parent class named HospitalEmployee.</p><h3>Inheritance III</h3><p>We’ve abstracted the shared properties and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> of our Cat and Dog classes into a parent class called Animal (See below).</p><pre>class Animal {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }<br>    <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>Now that we have these shared properties and methods in the parent Animal class, we can extend them to the subclass, Cat.</p><pre>class Cat extends Animal {<br>  constructor(name, usesLitter) {<br>    super(name);<br>    this._usesLitter = usesLitter;<br>  }<br>}</pre><p>In the example above, we create a new class named Cat that extends the Animal class. Let’s pay special attention to our new keywords: extends and super.</p><ul><li>The extends keyword makes the methods of the animal class available inside the cat class.</li><li>The constructor, called when you create a new Cat object, accepts two arguments, name and usesLitter.</li><li>The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it <a href="https://www.codecademy.com/resources/docs/javascript/sets">sets</a> this._name = name; for new Cat instances.</li><li>_usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.</li></ul><p>Notice, we call super on the first line of our constructor(), then set the usesLitter property on the second line. In a constructor(), you must always call the super method before you can use the <a href="https://www.codecademy.com/resources/docs/javascript/this">this</a> keyword — if you do not, JavaScript will throw a reference error. To avoid reference <a href="https://www.codecademy.com/resources/docs/javascript/errors">errors</a>, it is best practice to call super on the first line of subclass <a href="https://www.codecademy.com/resources/docs/javascript/constructors">constructors</a>.</p><p>Below, we create a new Cat instance and call its name with the same syntax as we did with the Dog class:</p><pre>const bryceCat = new Cat(&#39;Bryce&#39;, false); <br>console.log(bryceCat._name); // output: Bryce</pre><p>In the example above, we create a new instance the Cat class, named bryceCat. We pass it &#39;Bryce&#39; and false for our name and usesLitter arguments. When we call console.log(bryceCat._name) our program prints, Bryce.</p><p>In the example above, we abandoned best practices by calling our _name property directly. In the next exercise, we’ll address this by calling an inherited getter method for our name property.</p><h3>Inheritance IV</h3><p>Now that we know how to create an object that inherits properties from a parent class let’s turn our attention to <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>.</p><p>When we call extends in a class declaration, all of the parent methods are available to the child class.</p><p>Below, we extend our Animal class to a Cat subclass.</p><pre>class Animal {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }<br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>} <br><br>class Cat extends Animal {<br>  constructor(name, usesLitter) {<br>    super(name);<br>    this._usesLitter = usesLitter;<br>  }<br>}<br><br>const bryceCat = new Cat(&#39;Bryce&#39;, false);</pre><p>In the example above, our Cat class extends Animal. As a result, the Cat class has access to the Animal getters and the .incrementBehavior() method.</p><p>Also in the code above, we create a Cat instance named bryceCat. Because bryceCat has access to the name getter, the code below logs &#39;Bryce&#39; to the console.</p><pre>console.log(bryceCat.name);</pre><p>Since the extends keyword brings all of the parent’s getters and methods into the child class, bryceCat.name accesses the name getter and returns the value saved to the name property.</p><p>Now consider a more involved example and try to answer the following question: What will the code below log to the console?</p><pre>bryceCat.incrementBehavior(); // Call .incrementBehavior() on Cat instance <br>console.log(bryceCat.behavior); // Log value saved to behavior</pre><p>The correct answer is 1. But why?</p><ul><li>The Cat class inherits the _behavior property, behavior getter, and the .incrementBehavior() method from the Animal class.</li><li>When we created the bryceCat instance, the Animal constructor set the _behavior property to zero.</li><li>The first line of code calls the inherited .incrementBehavior() method, which increases the bryceCat _behavior value from zero to one.</li><li>The second line of code calls the behavior getter and logs the value saved to _behavior (1).</li></ul><h3>Inheritance V</h3><p>In addition to the inherited features, child classes can contain their own properties, getters, setters, and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>.</p><p>Below, we will add a usesLitter getter. The syntax for creating getters, setters, and methods is the same as it is in any other class.</p><pre>class Cat extends Animal {<br>  constructor(name, usesLitter) {<br>    super(name);<br>    this._usesLitter = usesLitter;<br>  }<br>    <br>  get usesLitter() {<br>    return this._usesLitter;<br>  }<br>}</pre><p>In the example above, we create a usesLitter getter in the Cat class that returns the value saved to _usesLitter.</p><p>Compare the Cat class above to the one we created without inheritance:</p><pre>class Cat {<br>  constructor(name, usesLitter) {<br>    this._name = name;<br>    this._usesLitter = usesLitter;<br>    this._behavior = 0;<br>  }<br>    <br>  get name() {<br>    return this._name;<br>  }<br>  <br>  get usesLitter() {<br>    return this._usesLitter;<br>  }<br>  <br>  get behavior() {<br>    return this._behavior;<br>  }   <br>  <br>  incrementBehavior() {<br>    this._behavior++;<br>  }<br>}</pre><p>We decreased the number of lines required to create the Cat class by about half. Yes, it did require an extra class (Animal), making the reduction in the size of our Cat class seem moot. However, the benefits (time saved, readability, efficiency) of inheritance grow as the number and size of your subclasses increase.</p><p>One benefit is that when you need to change a method or property that multiple classes share, you can change the parent class, instead of each subclass.</p><p>Before we move past inheritance, take a moment to see how we would create an additional subclass, called Dog.</p><pre>class Dog extends Animal {<br>  constructor(name) {<br>    super(name);<br>  }<br>}</pre><p>This Dog class has access to the same properties, getters, setters, and methods as the Dog class we made without inheritance, and is a quarter the size.</p><p>Now that we’ve abstracted animal daycare features, it’s easy to see how you can extend Animal to support other classes, like Rabbit, Bird or even Snake.</p><h3>Static Methods</h3><p>Sometimes you will want a class to have <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> that aren’t available in individual instances, but that you can call directly from the class.</p><p>Take the Date class, for example — you can both create Date instances to represent whatever date you want, and call <em>static</em> methods, like Date.now() which returns the current date, directly from the class. The <a href="https://www.codecademy.com/resources/docs/javascript/dates/now">.now()</a> method is static, so you can call it directly from the class, but not from an instance of the class.</p><p>Let’s see how to use the static keyword to create a static method called generateName method in our Animal class:</p><pre>class Animal {<br>  constructor(name) {<br>    this._name = name;<br>    this._behavior = 0;<br>  }<br>    <br>  static generateName() {<br>    const names = [&#39;Angel&#39;, &#39;Spike&#39;, &#39;Buffy&#39;, &#39;Willow&#39;, &#39;Tara&#39;];<br>    const randomNumber = Math.floor(Math.random()*5);<br>    return names[randomNumber];<br>  }<br>}</pre><p>In the example above, we create a static method called .generateName() that returns a random name when it’s called. Because of the static keyword, we can only access .generateName() by appending it to the Animal class.</p><p>We call the .generateName() method with the following syntax:</p><pre>console.log(Animal.generateName()); // returns a name</pre><p>You cannot access the .generateName() method from instances of the Animal class or instances of its subclasses (See below).</p><pre>const tyson = new Animal(&#39;Tyson&#39;); <br>tyson.generateName(); // TypeError</pre><p>The example above will result in an error, because you cannot call static methods (.generateName()) on an instance (tyson).</p><h3>Review: Classes</h3><p>Way to go! Let’s review what you learned.</p><ul><li><em>Classes</em> are templates for <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>.</li><li>Javascript calls a <em>constructor</em> method when we create a new instance of a class.</li><li><em>Inheritance</em> is when we create a parent class with properties and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> that we can extend to child classes.</li><li>We use the extends keyword to create a subclass.</li><li>The super keyword calls the constructor() of a parent class.</li><li>Static methods are called on the class, but not on instances of the class.</li></ul><p>In completing this lesson, you’ve taken one step closer to writing efficient, production-level JavaScript. Good luck as you continue to develop your skills and move into intermediate-level concepts.</p><p>QUIZES:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYGUkbMqYnL6a3qfIPlxyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15Xmict99m9PGDU9t8gDCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmOekfrysqP6hLAMjfdqyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7mQr_BMLp0EJGwV3Fo2eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSFtmCXXNiaA9eFSJDIehQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6siJ-QELjpS5E2Cj4JFp2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDBA-OtEn96iPmh8KcA34w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6fbf07a00c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — ADVANCED OBJECTS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-advanced-objects-db82f263ae41?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db82f263ae41</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 10:08:23 GMT</pubDate>
            <atom:updated>2023-08-20T10:08:23.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — <strong>ADVANCED OBJECTS</strong></h3><ul><li>how to use the <a href="https://www.codecademy.com/resources/docs/javascript/this">this</a> keyword.</li><li>conveying privacy in JavaScript <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>.</li><li>defining getters and setters in objects.</li><li>creating factory <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a>.</li><li>using destructuring techniques.</li></ul><h3>The this Keyword</h3><p><a href="https://www.codecademy.com/resources/docs/javascript/objects">Objects</a> are collections of related data and functionality. We store that functionality in <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> on our objects:</p><pre>const goat = {<br>  dietType: &#39;herbivore&#39;,<br>  makeSound() {<br>    console.log(&#39;baaa&#39;);<br>  }<br>};</pre><p>In our goat object we have a .makeSound() method. We can invoke the .makeSound() method on goat.</p><pre>goat.makeSound(); // Prints baaa</pre><p>Nice, we have a goat object that can print baaa to the console. Everything seems to be working fine. What if we wanted to add a new method to our goat object called .diet() that prints the goat‘s dietType?</p><pre>const goat = {<br>  dietType: &#39;herbivore&#39;,<br>  makeSound() {<br>    console.log(&#39;baaa&#39;);<br>  },<br>  diet() {<br>    console.log(dietType);<br>  }<br>};<br>goat.diet(); <br>// Output will be &quot;ReferenceError: dietType is not defined&quot;</pre><p>That’s strange, why is dietType not defined even though it’s a property of goat? That’s because inside the scope of the .diet() method, we don’t automatically have access to other properties of the goat object.</p><p>Here’s where the <a href="https://www.codecademy.com/resources/docs/javascript/this?page_ref=catalog">this</a> keyword comes to the rescue. If we change the .diet() method to use the this, the .diet() works! :</p><pre>const goat = {<br>  dietType: &#39;herbivore&#39;,<br>  makeSound() {<br>    console.log(&#39;baaa&#39;);<br>  },<br>  diet() {<br>    console.log(this.dietType);<br>  }<br>};<br><br>goat.diet(); <br>// Output: herbivore</pre><p>The this keyword references the <em>calling object</em> which provides access to the calling object’s properties. In the example above, the calling object is goat and by using this we’re accessing the goat object itself, and then the dietType property of goat by using property dot notation.</p><p>Let’s get comfortable using the this keyword in a method.</p><h3>Arrow Functions and this</h3><p>We saw in the previous exercise that for a method, the calling object is the object the method belongs to. If we use the <a href="https://www.codecademy.com/resources/docs/javascript/this?page_ref=catalog">this</a> keyword in a method then the value of this is the calling object. However, it becomes a bit more complicated when we start using arrow <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> for <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>. Take a look at the example below:</p><pre>const goat = {<br>  dietType: &#39;herbivore&#39;,<br>  makeSound() {<br>    console.log(&#39;baaa&#39;);<br>  },<br>  diet: () =&gt; {<br>    console.log(this.dietType);<br>  }<br>};<br><br>goat.diet(); // Prints undefined</pre><p>In the comment, you can see that goat.diet() would log undefined. So what happened? Notice that the .diet() method is defined using an arrow function.</p><p>Arrow functions inherently <em>bind</em>, or tie, an already defined this value to the function itself that is NOT the calling object. In the code snippet above, the value of this is the <em>global object</em>, or an object that exists in the global scope, which doesn’t have a dietType property and therefore returns undefined.</p><p>To read more about either arrow functions or the global object check out the MDN documentation of <a href="https://developer.mozilla.org/en-US/docs/Glossary/Global_object">the global object</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>.</p><p>The key takeaway from the example above is to <em>avoid</em> using arrow functions when using this in a method!</p><h3>Privacy</h3><p>Accessing and updating properties is fundamental in working with <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>. However, there are cases in which we don’t want other code simply accessing and updating an object’s properties. When discussing <em>privacy</em> in objects, we define it as the idea that only certain properties should be mutable or able to change in value.</p><p>Certain languages have privacy built-in for objects, but JavaScript does not have this feature. Rather, JavaScript developers follow naming conventions that signal to other developers how to interact with a property. One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered. Here’s an example of using _ to prepend a property.</p><pre>const bankAccount = {<br>  _amount: 1000<br>}</pre><p>In the example above, the _amount is not intended to be directly manipulated.</p><p>Even so, it is still possible to reassign _amount:</p><pre>bankAccount._amount = 1000000;</pre><p>In later exercises, we’ll cover the use of <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> called <em>getters</em> and <em>setters</em>. Both methods are used to respect the intention of properties prepended, or began, with _. Getters can return the value of internal properties and setters can safely reassign property values. For now, let’s see what happens if we can change properties that don’t have setters or getters.</p><h3>Getters</h3><p><em>Getters</em> are <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> that get and return the internal properties of an object. But they can do more than just retrieve the value of a property! Let’s take a look at a getter method:</p><pre>const person = {<br>  _firstName: &#39;John&#39;,<br>  _lastName: &#39;Doe&#39;,<br>  get fullName() {<br>    if (this._firstName &amp;&amp; this._lastName){<br>      return `${this._firstName} ${this._lastName}`;<br>    } else {<br>      return &#39;Missing a first name or a last name.&#39;;<br>    }<br>  }<br>}<br><br>// To call the getter method: <br>person.fullName; // &#39;John Doe&#39;</pre><p>Notice that in the getter method above:</p><ul><li>We use the get keyword followed by a function.</li><li>We use an if...else conditional to check if both _firstName and _lastName exist (by making sure they both return truthy values) and then return a different value depending on the result.</li><li>We can access the calling object’s internal properties using <a href="https://www.codecademy.com/resources/docs/javascript/this">this</a>. In fullName, we’re accessing both this._firstName and this._lastName.</li><li>In the last line we call fullName on person. In general, getter methods do not need to be called with a set of parentheses. Syntactically, it looks like we’re accessing a property.</li></ul><p>Now that we’ve gone over syntax, let’s discuss some notable advantages of using getter methods:</p><ul><li>Getters can perform an action on the data when getting a property.</li><li>Getters can return different values using <a href="https://www.codecademy.com/resources/docs/javascript/conditionals">conditionals</a>.</li><li>In a getter, we can access the properties of the calling object using this.</li><li>The functionality of our code is easier for other developers to understand.</li></ul><p>Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. If we do so, then calling the method will result in an infinite call stack error. One workaround is to add an underscore before the property name like we did in the example above.</p><p>Great, let’s go getter!</p><h3>Setters</h3><p>Along with getter <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>, we can also create <em>setter</em> methods which reassign values of existing properties within an object. Let’s see an example of a setter method:</p><pre>const person = {<br>  _age: 37,<br>  set age(newAge){<br>    if (typeof newAge === &#39;number&#39;){<br>      this._age = newAge;<br>    } else {<br>      console.log(&#39;You must assign a number to age&#39;);<br>    }<br>  }<br>};</pre><p>Notice that in the example above:</p><ul><li>We can perform a check for what value is being assigned to this._age.</li><li>When we use the setter method, only values that are numbers will reassign this._age</li><li>There are different outputs depending on what values are used to reassign this._age.</li></ul><p>Then to use the setter method:</p><pre>person.age = 40;<br>console.log(person._age); // Logs: 40<br>person.age = &#39;40&#39;; // Logs: You must assign a number to age<br><br>Setter methods like age do not need to be called with a set of parentheses. Syntactically, it looks like we’re reassigning the value of a property.</pre><p>Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used. Nonetheless, even with a setter method, it is still possible to directly reassign properties. For example, in the example above, we can still set ._age directly:</p><pre>person._age = &#39;forty-five&#39;<br>console.log(person._age); // Prints forty-five</pre><h3>Factory Functions</h3><p>So far we’ve been creating objects individually, but there are times where we want to create many instances of an object quickly. Here’s where <em>factory functions</em> come in. A real world factory manufactures multiple copies of an item quickly and on a massive scale. A factory function is a function that returns an object and can be reused to make multiple object instances. Factory functions can also have parameters allowing us to customize the object that gets returned.</p><p>Let’s say we wanted to create an object to represent monsters in JavaScript. There are many different types of monsters and we could go about making each monster individually but we can also use a factory function to make our lives easier. To achieve this diabolical plan of creating multiple monsters objects, we can use a factory function that has parameters:</p><pre>const monsterFactory = (name, age, energySource, catchPhrase) =&gt; {<br>  return { <br>    name: name,<br>    age: age, <br>    energySource: energySource,<br>    scare() {<br>      console.log(catchPhrase);<br>    } <br>  }<br>};</pre><p>In the monsterFactory function above, it has four parameters and returns an object that has the properties: name, age, energySource, and scare(). To make an object that represents a specific monster like a ghost, we can call monsterFactory with the necessary arguments and assign the return value to a variable:</p><pre>const ghost = monsterFactory(&#39;Ghouly&#39;, 251, &#39;ectoplasm&#39;, &#39;BOO!&#39;);<br>ghost.scare(); // &#39;BOO!&#39;</pre><p>Now we have a ghost object as a result of calling monsterFactory() with the needed arguments. With monsterFactory in place, we don’t have to create an object literal every time we need a new monster. Instead, we can invoke the monsterFactory function with the necessary arguments to take over the world make a monster for us!</p><h3>Property Value Shorthand</h3><p>ES6 introduced some new shortcuts for assigning properties to <a href="https://www.codecademy.com/resources/docs/javascript/variables">variables</a> known as <em>destructuring</em>.</p><p>In the previous exercise, we created a factory function that helped us create <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>. We had to assign each property a key and value even though the key name was the same as the parameter name we assigned to it. To remind ourselves, here’s a truncated version of the factory function:</p><pre>const monsterFactory = (name, age) =&gt; {<br>  return { <br>    name: name,<br>    age: age<br>  }<br>};</pre><p>Imagine if we had to include more properties, that process would quickly become tedious! But we can use a destructuring technique, called <em>property value shorthand</em>, to save ourselves some keystrokes. The example below works exactly like the example above:</p><pre>const monsterFactory = (name, age) =&gt; {<br>  return { <br>    name,<br>    age <br>  }<br>};</pre><p>Notice that we don’t have to repeat ourselves for property assignments!</p><h3>Destructured Assignment</h3><p>We often want to extract key-value pairs from <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> and save them as <a href="https://www.codecademy.com/resources/docs/javascript/variables">variables</a>. Take for example the following object:</p><pre>const vampire = {<br>  name: &#39;Dracula&#39;,<br>  residence: &#39;Transylvania&#39;,<br>  preferences: {<br>    day: &#39;stay inside&#39;,<br>    night: &#39;satisfy appetite&#39;<br>  }<br>};</pre><p>If we wanted to extract the residence property as a variable, we could use the following code:</p><pre>const residence = vampire.residence; <br>console.log(residence); // Prints &#39;Transylvania&#39;</pre><p>However, we can also take advantage of a destructuring technique called <em>destructured assignment</em> to save ourselves some keystrokes. In destructured assignment we create a variable with the name of an object’s key that is wrapped in curly braces { } and assign to it the object. Take a look at the example below:</p><pre>const { residence } = vampire; <br>console.log(residence); // Prints &#39;Transylvania&#39;</pre><p>Look back at the vampire object’s properties in the first code example. Then, in the example above, we declare a new variable residence that extracts the value of the residence property of vampire. When we log the value of residence to the console, &#39;Transylvania&#39; is printed.</p><p>We can even use destructured assignment to grab nested properties of an object:</p><pre>const { day } = vampire.preferences; <br>console.log(day); // Prints &#39;stay inside&#39;</pre><h3>Built-in Object Methods</h3><p>In the previous exercises we’ve been creating instances of <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> that have their own <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>. But, we can also take advantage of built-in methods for Objects!</p><p>For example, we have access to object instance methods like: .hasOwnProperty(), .valueOf(), and many more! Practice your documentation reading skills and check out: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods">MDN’s object instance documentation</a>.</p><p>There are also useful Object class methods such as Object.assign(), Object.entries(), and Object.keys() just to name a few. For a comprehensive list, browse: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor">MDN’s object instance documentation</a>.</p><p>Let’s get acquainted with some of these methods and their documentation.</p><p>Note: You will see <a href="https://www.codecademy.com/resources/docs/javascript/errors">errors</a> as you work through this exercise, but by the end the errors will be fixed!</p><h3>Review</h3><p>Congratulations on finishing Advanced Objects!</p><p>Let’s review the concepts covered in this lesson:</p><ul><li>The object that a method belongs to is called the <em>calling object</em>.</li><li>The <a href="https://www.codecademy.com/resources/docs/javascript/this">this</a> keyword refers to the calling object and can be used to access properties of the calling object.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/methods">Methods</a> do not automatically have access to other internal properties of the calling object.</li><li>The value of this depends on where the this is being accessed from.</li><li>We cannot use <a href="https://www.codecademy.com/resources/docs/javascript/arrow-functions">arrow functions</a> as methods if we want to access other internal properties.</li><li>JavaScript <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> do not have built-in privacy, rather there are conventions to follow to notify other developers about the intent of the code.</li><li>The usage of an underscore before a property name means that the original developer did not intend for that property to be directly changed.</li><li>Setters and getter methods allow for more detailed ways of accessing and assigning properties.</li><li>Factory <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> allow us to create object instances quickly and repeatedly.</li><li>There are different ways to use object destructuring: one way is the property value shorthand and another is destructured assignment.</li><li>As with any concept, it is a good skill to learn how to use the documentation with objects!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SixDhUVJJ5_0T69dxBRKtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPuqma15V42JD4T_kheWEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxMJk-v3A1B6mauunRuoqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bzN83QUhCvmJa5UqRrc7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0RLQZ-TePhW_onV448wTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnkRsw9IgrRKh3ICN0FG8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loYGb6FmT7KzgPK-q7CH3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsEOfKA81egoULu3LPUVCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0OBfUi4PHaF-pDdz8FV8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGFXRPcdqumm2sqYl5XPJQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db82f263ae41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS-OBJECTS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-objects-53f5ec581e80?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53f5ec581e80</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 06:33:36 GMT</pubDate>
            <atom:updated>2023-08-20T06:33:36.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Objects</h3><p>It’s time to learn more about the basic structure that permeates nearly every aspect of JavaScript programming: <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>.</p><p>You’re probably already more comfortable with objects than you think, because JavaScript loves objects! Many components of the language are actually objects under the hood, and even the parts that aren’t — like <a href="https://www.codecademy.com/resources/docs/javascript/strings">strings</a> or numbers — can still act like objects in some instances.</p><p>There are only seven fundamental <a href="https://www.codecademy.com/resources/docs/javascript/data-types">data types</a> in JavaScript, and six of those are the primitive data types: string, number, boolean, null, undefined, and symbol. With the seventh type, objects, we open our code to more complex possibilities. We can use JavaScript objects to model real-world things, like a basketball, or we can use objects to build the data structures that make the web possible.</p><p>At their core, JavaScript objects are containers storing related data and functionality, but that deceptively simple task is extremely powerful in practice. You’ve been using the power of objects all along, but now it’s time to understand the mechanics of objects and start making your own!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXeFaNC-nAT_eB2Mv61R4A.png" /></figure><h3>Creating Object Literals</h3><p>Objects can be assigned to variables just like any JavaScript type. We use curly braces, {}, to designate an <em>object literal</em>:</p><pre>let spaceship = {}; // spaceship is an empty object</pre><p>We fill an object with unordered data. This data is organized into <em>key-value pairs</em>. A key is like a variable name that points to a location in memory that holds a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*dO0gjEKsAz2VndkKShJPHw.png" /></figure><p>A key’s value can be of any data type in the language including functions or other objects.</p><p>We make a key-value pair by writing the key’s name, or <em>identifier</em>, followed by a colon and then the value. We separate each key-value pair in an object literal with a comma (,). Keys are strings, but when we have a key that does not have any special characters in it, JavaScript allows us to omit the quotation marks:</p><pre>// An object literal with two key-value pairs<br>let spaceship = {<br>  &#39;Fuel Type&#39;: &#39;diesel&#39;,<br>  color: &#39;silver&#39;<br>};</pre><p>The spaceship object has two properties Fuel Type and color. &#39;Fuel Type&#39; has quotation marks because it contains a space character.</p><p>Let’s make some objects!</p><h3>Accessing Properties</h3><p>There are two ways we can access an object’s property. Let’s explore the first way — dot notation, ..</p><p>You’ve used dot notation to access the properties and methods of built-in objects and data instances:</p><pre>&#39;hello&#39;.length; // Returns 5</pre><p>With property dot notation, we write the object’s name, followed by the dot operator and then the property name (key):</p><pre>let spaceship = {<br>  homePlanet: &#39;Earth&#39;,<br>  color: &#39;silver&#39;<br>};<br>spaceship.homePlanet; // Returns &#39;Earth&#39;,<br>spaceship.color; // Returns &#39;silver&#39;,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*k1epbqouK950H6eeMqT6YA.png" /></figure><p>If we try to access a property that does not exist on that object, undefined will be returned.</p><pre>spaceship.favoriteIcecream; // Returns undefined</pre><p>Let’s get some more practice using dot notation on an object!</p><h3>Bracket Notation</h3><p>The second way to access a key’s value is by using bracket notation, [ ].</p><p>You’ve used bracket notation when indexing an array:</p><pre>[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;][0]; // Returns &#39;A&#39;</pre><p>To use bracket notation to access an object’s property, we pass in the property name (key) as a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*HZOkIWp2e18A-Co-9eXtuA.png" /></figure><p>We <strong>must</strong> use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error.</p><pre>let spaceship = {<br>  &#39;Fuel Type&#39;: &#39;Turbo Fuel&#39;,<br>  &#39;Active Duty&#39;: true,<br>  homePlanet: &#39;Earth&#39;,<br>  numCrew: 5<br>};<br>spaceship[&#39;Active Duty&#39;];   // Returns true<br>spaceship[&#39;Fuel Type&#39;];   // Returns  &#39;Turbo Fuel&#39;<br>spaceship[&#39;numCrew&#39;];   // Returns 5<br>spaceship[&#39;!!!!!!!!!!!!!!!&#39;];   // Returns undefined</pre><p>With bracket notation you can also use a variable inside the brackets to select the keys of an object. This can be especially helpful when working with functions:</p><pre>let returnAnyProp = (objectName, propName) =&gt; objectName[propName];<br> <br>returnAnyProp(spaceship, &#39;homePlanet&#39;); // Returns &#39;Earth&#39;</pre><p>If we tried to write our returnAnyProp() function with dot notation (objectName.propName) the computer would look for a key of &#39;propName&#39; on our object and not the value of the propName parameter.</p><p>Let’s get some practice using bracket notation to access properties!</p><h3>Property Assignment</h3><p>Once we’ve defined an object, we’re not stuck with all the properties we wrote. <a href="https://www.codecademy.com/resources/docs/javascript/objects">Objects</a> are <em>mutable</em> meaning we can update them after we create them!</p><p>We can use either dot notation, ., or bracket notation, [], and the assignment operator, = to add new key-value pairs to an object or change an existing property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*D8fQjZ4x7enwQ42Yj4YM0A.png" /></figure><p>One of two things can happen with property assignment:</p><ul><li>If the property already exists on the object, whatever value it held before will be replaced with the newly assigned value.</li><li>If there was no property with that name, a new property will be added to the object.</li></ul><p>It’s important to know that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.</p><pre>const spaceship = {type: &#39;shuttle&#39;};<br>spaceship = {type: &#39;alien&#39;}; // TypeError: Assignment to constant variable.<br>spaceship.type = &#39;alien&#39;; // Changes the value of the type property<br>spaceship.speed = &#39;Mach 5&#39;; // Creates a new key of &#39;speed&#39; with a value of &#39;Mach 5&#39;</pre><p>You can delete a property from an object with the delete operator.</p><pre>const spaceship = {<br>  &#39;Fuel Type&#39;: &#39;Turbo Fuel&#39;,<br>  homePlanet: &#39;Earth&#39;,<br>  mission: &#39;Explore the universe&#39; <br>};<br> <br>delete spaceship.mission;  // Removes the mission property</pre><h3>Methods</h3><p>When the data stored on an object is a function we call that a <a href="https://www.codecademy.com/resources/docs/javascript/methods?page_ref=catalog"><em>method</em></a>. A property is what an object has, while a method is what an object does.</p><p>Do object methods seem familiar? That’s because you’ve been using them all along! For example console is a global JavaScript object and .log() is a method on that object. Math is also a global JavaScript object and .floor() is a method on it.</p><p>We can include methods in our object literals by creating ordinary, colon-separated key-value pairs. The key serves as our method’s name, while the value is an anonymous function expression.</p><pre>const alienShip = {<br>  invade: function () { <br>    console.log(&#39;Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.&#39;)<br>  }<br>};</pre><p>With the new method syntax introduced in ES6 we can omit the colon and the function keyword.</p><pre>const alienShip = {<br>  invade () { <br>    console.log(&#39;Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.&#39;)<br>  }<br>};</pre><p>Object methods are invoked by appending the object’s name with the dot operator followed by the method name and parentheses:</p><pre>alienShip.invade(); // Prints &#39;Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.&#39;</pre><h3>Nested Objects</h3><p>In application code, <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> are often nested — an object might have another object as a property which in turn could have a property that’s an array of even more objects!</p><p>In our spaceship object, we want a crew object. This will contain all the crew members who do important work on the craft. Each of those crew members are objects themselves. They have properties like name, and degree, and they each have unique <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> based on their roles. We can also nest other objects in the spaceship such as a telescope or nest details about the spaceship’s computers inside a parent nanoelectronics object.</p><pre>const spaceship = {<br>     telescope: {<br>        yearBuilt: 2018,<br>        model: &#39;91031-XLT&#39;,<br>        focalLength: 2032 <br>     },<br>    crew: {<br>        captain: { <br>            name: &#39;Sandra&#39;, <br>            degree: &#39;Computer Engineering&#39;, <br>            encourageTeam() { console.log(&#39;We got this!&#39;) } <br>         }<br>    },<br>    engine: {<br>        model: &#39;Nimbus2000&#39;<br>     },<br>     nanoelectronics: {<br>         computer: {<br>            terabytes: 100,<br>            monitors: &#39;HD&#39;<br>         },<br>        &#39;back-up&#39;: {<br>           battery: &#39;Lithium&#39;,<br>           terabytes: 50<br>         }<br>    }<br>};</pre><p>We can chain <a href="https://www.codecademy.com/resources/docs/javascript/operators">operators</a> to access nested properties. We’ll have to pay attention to which operator makes sense to use in each layer. It can be helpful to pretend you are the computer and evaluate each expression from left to right so that each operation starts to feel a little more manageable.</p><pre>spaceship.nanoelectronics[&#39;back-up&#39;].battery; // Returns &#39;Lithium&#39;</pre><p>In the preceding code:</p><ul><li>First the computer evaluates spaceship.nanoelectronics, which results in an object containing the back-up and computer objects.</li><li>We accessed the back-up object by appending [&#39;back-up&#39;].</li><li>The back-up object has a battery property, accessed with .battery which returned the value stored there: &#39;Lithium&#39;</li></ul><h3>Pass By Reference</h3><p><a href="https://www.codecademy.com/resources/docs/javascript/objects">Objects</a> are <em>passed by reference</em>. This means when we pass a variable assigned to an object into a function as an argument, the computer interprets the parameter name as pointing to the space in memory holding that object. As a result, <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> which change object properties actually mutate the object permanently (even when the object is assigned to a const variable).</p><pre>const spaceship = {<br>  homePlanet : &#39;Earth&#39;,<br>  color : &#39;silver&#39;<br>};<br> <br>let paintIt = obj =&gt; {<br>  obj.color = &#39;glorious gold&#39;<br>};<br> <br>paintIt(spaceship);<br> <br>spaceship.color // Returns &#39;glorious gold&#39;</pre><p>Our function paintIt() permanently changed the color of our spaceship object. However, reassignment of the spaceship variable wouldn’t work in the same way:</p><pre>let spaceship = {<br>  homePlanet : &#39;Earth&#39;,<br>  color : &#39;red&#39;<br>};<br>let tryReassignment = obj =&gt; {<br>  obj = {<br>    identified : false, <br>    &#39;transport type&#39; : &#39;flying&#39;<br>  }<br>  console.log(obj) // Prints {&#39;identified&#39;: false, &#39;transport type&#39;: &#39;flying&#39;}<br> <br>};<br>tryReassignment(spaceship) // The attempt at reassignment does not work.<br>spaceship // Still returns {homePlanet : &#39;Earth&#39;, color : &#39;red&#39;};<br> <br>spaceship = {<br>  identified : false, <br>  &#39;transport type&#39;: &#39;flying&#39;<br>}; // Regular reassignment still works.</pre><p>Let’s look at what happened in the code example:</p><ul><li>We declared this spaceship object with let. This allowed us to reassign it to a new object with identified and &#39;transport type&#39; properties with no problems.</li><li>When we tried the same thing using a function designed to reassign the object passed into it, the reassignment didn’t stick (even though calling console.log() on the object produced the expected result).</li><li>When we passed spaceship into that function, obj became a reference to the memory location of the spaceship object, but <em>not</em> to the spaceship variable. This is because the obj parameter of the tryReassignment() function is a variable in its own right. The body of tryReassignment() has no knowledge of the spaceship variable at all!</li><li>When we did the reassignment in the body of tryReassignment(), the obj variable came to refer to the memory location of the object {&#39;identified&#39; : false, &#39;transport type&#39; : &#39;flying&#39;}, while the spaceship variable was completely unchanged from its earlier value.</li></ul><h3>Looping Through Objects</h3><p><a href="https://www.codecademy.com/resources/docs/javascript/loops">Loops</a> are programming tools that repeat a block of code until a condition is met. We learned how to iterate through <a href="https://www.codecademy.com/resources/docs/javascript/arrays">arrays</a> using their numerical indexing, but the key-value pairs in <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> aren’t ordered! <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">JavaScript has given us alternative solution for iterating through objects with the </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in syntax </a>.</p><p>for...in will execute a given block of code for each property in an object.</p><pre>let spaceship = {<br>  crew: {<br>    captain: { <br>      name: &#39;Lily&#39;, <br>      degree: &#39;Computer Engineering&#39;, <br>      cheerTeam() { console.log(&#39;You got this!&#39;) } <br>    },<br>    &#39;chief officer&#39;: { <br>      name: &#39;Dan&#39;, <br>      degree: &#39;Aerospace Engineering&#39;, <br>      agree() { console.log(&#39;I agree, captain!&#39;) } <br>    },<br>    medic: { <br>      name: &#39;Clementine&#39;, <br>      degree: &#39;Physics&#39;, <br>      announce() { console.log(`Jets on!`) } },<br>    translator: {<br>      name: &#39;Shauna&#39;, <br>      degree: &#39;Conservation Science&#39;, <br>      powerFuel() { console.log(&#39;The tank is full!&#39;) } <br>    }<br>  }<br>}; <br><br>// for...in<br>for (let crewMember in spaceship.crew) {<br>  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);<br>}</pre><p>Our for...in will iterate through each element of the spaceship.crew object. In each iteration, the variable crewMember is set to one of spaceship.crew‘s keys, enabling us to log a list of crew members’ role and name.</p><h3>Review</h3><p>Way to go! You’re well on your way to understanding the mechanics of <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> in JavaScript. By building your own objects, you will have a better understanding of how JavaScript built-in objects work as well. You can also start imagining organizing your code into objects and modeling real world things in code.</p><p>Let’s review what we learned in this lesson:</p><ul><li>Objects store collections of <em>key-value</em> pairs.</li><li>Each key-value pair is a property — when a property is a function it is known as a method.</li><li>An object literal is composed of comma-separated key-value pairs surrounded by curly braces.</li><li>You can access, add or edit a property within an object by using dot notation or bracket notation.</li><li>We can add <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> to our object literals using key-value syntax with anonymous function expressions as values or by using the new ES6 method syntax.</li><li>We can navigate complex, nested objects by chaining <a href="https://www.codecademy.com/resources/docs/javascript/operators">operators</a>.</li><li>Objects are mutable — we can change their properties even when they’re declared with const.</li><li>Objects are passed by reference — when we make changes to an object passed into a function, those changes are permanent.</li><li>We can iterate through objects using the For...in syntax.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53f5ec581e80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — ITERATORS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-iterators-f1234deab6de?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1234deab6de</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 20:18:52 GMT</pubDate>
            <atom:updated>2023-08-19T20:18:52.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — <strong>ITERATORS</strong></h3><h3>Introduction to Iterators</h3><p>Imagine you had a grocery list and you wanted to know what each item on the list was. You’d have to scan through each row and check for the item. This common task is similar to what we have to do when we want to iterate over, or loop through, an array. One tool at our disposal is the for loop. However, we also have access to built-in array <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> which make looping easier.</p><p>The built-in JavaScript array methods that help us iterate are called <em>iteration methods</em>, at times referred to as <a href="https://www.codecademy.com/resources/docs/javascript/iterators"><em>iterators</em></a>. Iterators are methods called on <a href="https://www.codecademy.com/resources/docs/javascript/arrays">arrays</a> to manipulate elements and return values.</p><p>In this lesson, you will learn the syntax for these methods, their return values, how to use the documentation to understand them, and how to choose the right iterator method for a given task.</p><p>Inspect the code in <strong>main.js</strong>. Notice the different methods being called on the arrays:</p><ul><li>.forEach()</li><li>.map()</li><li>.filter()</li></ul><p>Run the code to see the output!</p><h3>The .forEach() Method</h3><p>The first iteration method that we’re going to learn is <a href="https://www.codecademy.com/resources/docs/javascript/arrays/forEach?page_ref=catalog">.forEach()</a>. Aptly named, .forEach() will execute the same code for each element of an array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*DHkK5v094pp7Asyw7Qhcvw.png" /></figure><p>The code above will log a nicely formatted list of the groceries to the console. Let’s explore the syntax of invoking .forEach().</p><ul><li>groceries.forEach() calls the forEach method on the groceries array.</li><li>.forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function.</li><li>.forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function.</li><li>The return value for .forEach() will always be undefined.</li></ul><p>Another way to pass a callback for .forEach() is to use arrow function syntax.</p><pre>groceries.forEach(groceryItem =&gt; console.log(groceryItem));</pre><p>We can also define a function beforehand to be used as the callback function.</p><pre>function printGrocery(element){<br>  console.log(element);<br>}<br><br>groceries.forEach(printGrocery);</pre><p>The above example uses a function declaration but you can also use a function expression or arrow function as well.</p><p>All three code snippets do the same thing. In each array iteration method, we can use any of the three examples to supply a callback function as an argument to the iterator. It’s good to be aware of the different ways to pass in callback functions as arguments in iterators because developers have different stylistic preferences. Nonetheless, due to the strong adoption of ES6, we will be using arrow function syntax in the later exercises.</p><h3>The .map() Method</h3><p>The second iterator we’re going to cover is .map(). When <a href="https://www.codecademy.com/resources/docs/javascript/arrays/map?page_ref=catalog">.map()</a> is called on an array, it takes an argument of a callback function and returns a new array! Take a look at an example of calling .map():</p><pre>const numbers = [1, 2, 3, 4, 5]; <br><br>const bigNumbers = numbers.map(number =&gt; {<br>  return number * 10;<br>});</pre><p>.map() works in a similar manner to <a href="https://www.codecademy.com/resources/docs/javascript/arrays/forEach">.forEach()</a>— the major difference is that .map() returns a new array.</p><p>In the example above:</p><ul><li>numbers is an array of numbers.</li><li>bigNumbers will store the return value of calling .map() on numbers.</li><li>numbers.map will iterate through each element in the numbers array and pass the element into the callback function.</li><li>return number * 10 is the code we wish to execute upon each element in the array. This will save each value from the numbers array, multiplied by 10, to a new array.</li></ul><p>If we take a look at numbers and bigNumbers:</p><pre>console.log(numbers); // Output: [1, 2, 3, 4, 5]<br>console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]</pre><p>Notice that the elements in numbers were not altered and bigNumbers is a new array.The .filter() Method</p><p>Another useful iterator method is <a href="https://www.codecademy.com/resources/docs/javascript/arrays/filter?page_ref=catalog">.filter()</a>. Like <a href="https://www.codecademy.com/resources/docs/javascript/arrays/map">.map()</a>, .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:</p><pre>const words = [&#39;chair&#39;, &#39;music&#39;, &#39;pillow&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]; <br><br>const shortWords = words.filter(word =&gt; {<br>  return word.length &lt; 6;<br>});</pre><ul><li>words is an array that contains string elements.</li><li>const shortWords = declares a new variable that will store the returned array from invoking .filter().</li><li>The callback function is an arrow function that has a single parameter, word. Each element in the words array will be passed to this function as an argument.</li><li>word.length &lt; 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters will be added to the shortWords array.</li></ul><p>Let’s also check the values of words and shortWords:</p><pre>console.log(words); // Output: [&#39;chair&#39;, &#39;music&#39;, &#39;pillow&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]; <br>console.log(shortWords); // Output: [&#39;chair&#39;, &#39;music&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]</pre><p>Observe how words was not mutated, i.e. changed, and shortWords is a new array.</p><h3>The .filter() Method</h3><p>Another useful iterator method is <a href="https://www.codecademy.com/resources/docs/javascript/arrays/filter?page_ref=catalog">.filter()</a>. Like <a href="https://www.codecademy.com/resources/docs/javascript/arrays/map">.map()</a>, .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:</p><pre>const words = [&#39;chair&#39;, &#39;music&#39;, &#39;pillow&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]; <br><br>const shortWords = words.filter(word =&gt; {<br>  return word.length &lt; 6;<br>});</pre><ul><li>words is an array that contains string elements.</li><li>const shortWords = declares a new variable that will store the returned array from invoking .filter().</li><li>The callback function is an arrow function that has a single parameter, word. Each element in the words array will be passed to this function as an argument.</li><li>word.length &lt; 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters will be added to the shortWords array.</li></ul><p>Let’s also check the values of words and shortWords:</p><pre>console.log(words); // Output: [&#39;chair&#39;, &#39;music&#39;, &#39;pillow&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]; <br>console.log(shortWords); // Output: [&#39;chair&#39;, &#39;music&#39;, &#39;brick&#39;, &#39;pen&#39;, &#39;door&#39;]</pre><h3>The .findIndex() Method</h3><p>We sometimes want to find the location of an element in an array. That’s where the .findIndex() method comes in! Calling <a href="https://www.codecademy.com/resources/docs/javascript/arrays/findIndex?page_ref=catalog">.findIndex()</a> on an array will return the index of the first element that evaluates to true in the callback function.</p><pre>const jumbledNums = [123, 25, 78, 5, 9]; <br><br>const lessThanTen = jumbledNums.findIndex(num =&gt; {<br>  return num &lt; 10;<br>});</pre><ul><li>jumbledNums is an array that contains elements that are numbers.</li><li>const lessThanTen = declares a new variable that stores the returned index number from invoking .findIndex().</li><li>The callback function is an arrow function that has a single parameter, num. Each element in the jumbledNums array will be passed to this function as an argument.</li><li>num &lt; 10; is the condition that elements are checked against. .findIndex() will return the index of the first element which evaluates to true for that condition.</li></ul><p>Let’s take a look at what lessThanTen evaluates to:</p><pre>console.log(lessThanTen); // Output: 3</pre><p>If we check what element has index of 3:</p><pre>console.log(jumbledNums[3]); // Output: 5</pre><p>Great, the element in index 3 is the number 5. This makes sense since 5 is the first element that is less than 10.</p><p>If there isn’t a single element in the array that satisfies the condition in the callback, then .findIndex() will return -1.</p><pre>const greaterThan1000 = jumbledNums.findIndex(num =&gt; {<br>  return num &gt; 1000;<br>});<br><br>console.log(greaterThan1000); // Output: -1</pre><h3>The .reduce() Method</h3><p>Another widely used iteration method is .reduce(). The <a href="https://www.codecademy.com/resources/docs/javascript/arrays/reduce?page_ref=catalog">.reduce()</a> method returns a single value after iterating through the elements of an array, thereby <em>reducing</em> the array. Take a look at the example below:</p><pre>const numbers = [1, 2, 4, 10];<br><br>const summedNums = numbers.reduce((accumulator, currentValue) =&gt; {<br>  return accumulator + currentValue<br>})</pre><pre>console.log(summedNums) // Output: 17</pre><p>Here are the values of accumulator and currentValue as we iterate through the numbers array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F5dcHb6mALHIsLopmkmPQ.png" /></figure><p>Now let’s go over the use of .reduce() from the example above:</p><ul><li>numbers is an array that contains numbers.</li><li>summedNums is a variable that stores the returned value of invoking .reduce() on numbers.</li><li>numbers.reduce() calls the .reduce() method on the numbers array and takes in a callback function as argument.</li><li>The callback function has two parameters, accumulator and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element. To see the value of accumulator and currentValue change, review the chart above.</li><li>As .reduce() iterates through the array, the return value of the callback function becomes the accumulator value for the next iteration, currentValue takes on the value of the current element in the looping process.</li></ul><p>The .reduce() method can also take an optional second parameter to set an initial value for accumulator (remember, the first argument is the callback function!). For instance:</p><pre>const numbers = [1, 2, 4, 10];<br><br>const summedNums = numbers.reduce((accumulator, currentValue) =&gt; {<br>  return accumulator + currentValue<br>}, 100)  // &lt;- Second argument for .reduce()<br><br>console.log(summedNums); // Output: 117</pre><p>Here’s an updated chart that accounts for the second argument of 100:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4K48mpMSEm8O5aTnj3NDw.png" /></figure><h3>Iterator Documentation</h3><p>There are many additional built-in array <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>, a complete list of which is on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods">MDN’s Array iteration methods page</a>.</p><p>The documentation for each method contains several sections:</p><ol><li>A short definition.</li><li>A block with the correct syntax for using the method.</li><li>A list of parameters the method accepts or requires.</li><li>The return value of the function.</li><li>An extended description.</li><li>Examples of the method’s use.</li><li>Other additional information.</li></ol><p>In the instructions below, there are some <a href="https://www.codecademy.com/resources/docs/javascript/errors">errors</a> in the code. Use the documentation for a given method to determine the error or fill in a blank to make the code run correctly.</p><h3>Choose the Right Iterator</h3><p>There are many iteration <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> you can choose. In addition to learning the correct syntax for the use of iteration methods, it is also important to learn how to choose the correct method for different scenarios. The exercises below will give you the opportunity to do just that!</p><p>You’ll see <a href="https://www.codecademy.com/resources/docs/javascript/errors">errors</a> pop up in the terminal as you work through this exercise, but by the end the errors will be gone!</p><pre>const cities = [&#39;Orlando&#39;, &#39;Dubai&#39;, &#39;Edinburgh&#39;, &#39;Chennai&#39;, &#39;Accra&#39;, &#39;Denver&#39;, &#39;Eskisehir&#39;, &#39;Medellin&#39;, &#39;Yokohama&#39;];<br><br>const nums = [1, 50, 75, 200, 350, 525, 1000];<br><br>//  Choose a method that will return undefined<br>cities.forEach(city =&gt; console.log(&#39;Have you visited &#39; + city + &#39;?&#39;));<br><br>// Choose a method that will return a new array<br>const longCities = cities.filter(city =&gt; city.length &gt; 7);<br><br>// Choose a method that will return a single value<br>const word = cities.reduce((acc, currVal) =&gt; {<br>  return acc + currVal[0]<br>}, &quot;C&quot;);<br><br>console.log(word)<br><br>// Choose a method that will return a new array<br>const smallerNums = nums.map(num =&gt; num - 5);<br><br>// Choose a method that will return a boolean value<br>nums.every(num =&gt; num &lt; 0);<br>// OR nums.some(num =&gt; num &lt; 0);</pre><h3>Review</h3><p>Awesome job on clearing the <a href="https://www.codecademy.com/resources/docs/javascript/iterators">iterators</a> lesson! You have learned a number of useful <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> in this lesson as well as how to use the JavaScript documentation from the Mozilla Developer Network to discover and understand additional methods. Let’s review!</p><ul><li><a href="https://www.codecademy.com/resources/docs/javascript/arrays/forEach">.forEach()</a> is used to execute the same code on every element in an array but does not change the array and returns undefined.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/arrays/map">.map()</a> executes the same code on every element in an array and returns a new array with the updated elements.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/arrays/filter">.filter()</a> checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/arrays/findIndex">.findIndex()</a> returns the index of the first element of an array that satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/arrays/reduce">.reduce()</a> iterates through an array and takes the values of the elements and returns a single value.</li><li>All iterator methods take a callback function, which can be a pre-defined function, a function expression, or an arrow function.</li><li>You can visit the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Mozilla Developer Network</a> to learn more about iterator methods (and all other parts of JavaScript!).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eINXjYOyThw7oW7yFpj-xQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duIwArWbJ2PgtZl1k0P1NQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SILw7vixnMn74QC8aEP_Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VNxwutjmwj9pKqjls2Tlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS1k4kEc7YUCC5wg4fXUKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3hdX3EnMpdZuav_NWFLVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRROpscB98-QNtXlraz8wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQjWQEJxvLDNCvfRQ_GCIA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1234deab6de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — HIGHER-ORDER FUNCTIONS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/higher-order-functions-31d054149cdd?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d054149cdd</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 19:05:10 GMT</pubDate>
            <atom:updated>2023-08-19T19:05:26.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>We are often unaware of the number of assumptions we make when communicating in our native languages. If we told you to “count to three,” we would expect you to say the numbers “one”, “two”, and “three”. We assumed you would know to start with “one” and end with “three”. With programming, we need to be more explicit with our directions to the computer. Here’s how we might tell the computer to “count to three”:</p><pre>for (let i = 1; i &lt;= 3; i++) {<br>  console.log(i);<br>}</pre><p>When we speak to other humans, we share a vocabulary that provides quick ways to communicate complicated concepts. When we say the word “bake”, it calls to mind a familiar subroutine — preheating an oven, putting something into an oven for a set amount of time, and finally removing it. This allows us to <em>abstract</em> away a lot of the details and communicate key concepts more concisely. Instead of listing all those details, we can say, “We baked a cake,” and still impart all that meaning to you.</p><p>In this lesson, we’ll learn how to use “abstraction” in programming by writing <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a>. In addition to allowing us to reuse our code, functions help to make clear, readable programs. If you encounter countToThree() in a program, you might be able to quickly guess what the function does without having to stop and read the function’s body.</p><p>We’re also going to learn about a way to add another level of abstraction to our programming: <em>higher-order functions</em>. <em>Higher-order functions</em> are functions that accept other functions as arguments and/or return functions as output. This enables us to build abstractions on other abstractions, just like “We hosted a birthday party” is an abstraction that may build on the abstraction “We made a cake.”</p><h3>Functions as Data</h3><p>JavaScript <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> behave like any other data type in the language; we can assign functions to <a href="https://www.codecademy.com/resources/docs/javascript/variables">variables</a>, and we can reassign them to new variables.</p><p>Below, we have an annoyingly long function name that hurts the readability of any code in which it’s used. Note: If the below function’s syntax feels unfamiliar, revisit the <a href="https://www.codecademy.com/courses/introduction-to-javascript/lessons/functions/exercises/arrow-functions">arrow functions exercise</a> to refresh your knowledge on ES6 arrow notation.</p><pre>const announceThatIAmDoingImportantWork = () =&gt; {<br>    console.log(&quot;I’m doing very important work!&quot;);<br>};</pre><p>Let’s pretend this function does important work and needs to be called repeatedly. To rename this function without sacrificing the source code, we can re-assign the function to a variable with a suitably short name:</p><pre>const busy = announceThatIAmDoingImportantWork;<br><br>busy(); // This function call barely takes any space!</pre><p>busy is a variable that holds a <em>reference</em> to our original function. If we could look up the address in memory of busy and the address in memory of announceThatIAmDoingImportantWork they would point to the same place. Our new busy() function can be invoked with parentheses as if that was the name we originally gave our function.</p><p>Notice how we assign announceThatIAmDoingImportantWork without parentheses as the value to the busy variable. We want to assign the value of the function itself, not the value it returns when invoked.</p><p>In JavaScript, functions are <em>first class objects</em>. This means that, like other <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a> you’ve encountered, JavaScript functions can have properties and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>.</p><p>Since functions are a type of object, they have properties such as .length and .name, and methods such as .toString(). You can see more about the methods and properties of functions <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">in the documentation</a>.</p><p>Functions are special because we can invoke them, but we can still treat them like any other type of data. Let’s get some practice doing that!</p><h3>Functions as Parameters</h3><p>As you know, a <a href="https://www.codecademy.com/courses/introduction-to-javascript/lessons/functions/exercises/parameters">parameter</a> is a placeholder for the data that gets passed into a function. Since <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> can behave like any other type of data in JavaScript, it might not surprise you to learn that functions can accept other functions as parameters. A <em>higher-order function</em> is a function that either accepts functions as parameters, returns a function, or both! We call functions that get passed in as parameters <em>callback functions</em>. Callback functions get invoked during the execution of the higher-order function.</p><p>When we invoke a higher-order function, and pass another function in as an argument, we don’t invoke the argument function. Invoking it would evaluate to passing in the return value of that function call. With callback functions, we pass in the function itself by typing the function name <em>without</em> the parentheses:</p><pre>const higherOrderFunc = param =&gt; {<br>  param();<br>  return `I just invoked ${param.name} as a callback function!`<br>}<br> <br>const anotherFunc = () =&gt; {<br>  return &#39;I\&#39;m being invoked by the higher-order function!&#39;;<br>}<br><br>higherOrderFunc(anotherFunc);</pre><p>We wrote a higher-order function higherOrderFunc that accepts a single parameter, param. Inside the body, param gets invoked using parentheses. And finally, a string is returned, telling us the name of the callback function that was passed in.</p><p>Below the higher-order function, we have another function aptly named anotherFunc. This function aspires to be called inside the higher-order function.</p><p>Lastly, we invoke higherOrderFunc(), passing in anotherFunc as its argument, thus fulfilling its dreams of being called by the higher-order function.</p><pre>higherOrderFunc(() =&gt; {<br>  for (let i = 0; i &lt;= 10; i++){<br>    console.log(i);<br>  }<br>});</pre><p>In this example, we invoked higherOrderFunc() with an <a href="https://www.codecademy.com/courses/introduction-to-javascript/lessons/functions/exercises/function-expressions">anonymous function</a> (a function without a name) that counts to 10. Anonymous functions can be arguments too!</p><h3>Review</h3><p>Great job! By thinking about <a href="https://www.codecademy.com/resources/docs/javascript/functions">functions</a> as data, and learning about higher-order functions, you’ve taken important steps in learning to write clean, modular code that takes advantage of JavaScript’s flexibility.</p><p>Let’s review what we learned in this lesson:</p><ul><li>Abstraction allows us to write complicated code in a way that’s easy to reuse, debug, and understand for human readers.</li><li>We can work with functions the same way we work with any other type of data, including reassigning them to new <a href="https://www.codecademy.com/resources/docs/javascript/variables">variables</a>.</li><li>JavaScript functions are first-class <a href="https://www.codecademy.com/resources/docs/javascript/objects">objects</a>, so they have properties and <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> like any other object.</li><li>Functions can be passed into other functions as parameters.</li><li>A higher-order function is a function that either accepts functions as parameters, returns a function, or both.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d054149cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — LOOPS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-loops-3361818d1e75?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3361818d1e75</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 18:55:00 GMT</pubDate>
            <atom:updated>2023-08-19T18:55:00.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — LOOPS</h3><h3>Loops</h3><p>A <em>loop</em> is a programming tool that repeats a set of instructions until a specified condition, called a <em>stopping condition</em> is reached. As a programmer, you’ll find that you rely on <a href="https://www.codecademy.com/resources/docs/javascript/loops">loops</a> all the time! You’ll hear the generic term <em>iterate</em> when referring to loops; iterate simply means “to repeat”.</p><p>When we need to reuse a task in our code, we often bundle that action in a function. Similarly, when we see that a process has to repeat multiple times in a row, we write a loop. Loops allow us to create efficient code that automates processes to make scalable, manageable programs.</p><p>As illustrated in the diagram, loops iterate or repeat an action until a specific condition is met. When the condition is met, the loop stops and the computer moves on to the next part of the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEmhNwD0zsZJ4ODZVNnIEA.png" /></figure><h3>Repeating Tasks Manually</h3><p>Before we write our own <a href="https://www.codecademy.com/resources/docs/javascript/loops">loops</a> let’s take a moment to develop an appreciation for loops. The best way to do that is by showing you how cumbersome it would be if a repeated task required you to type out the same code every single time.</p><h3>The For Loop</h3><p>Instead of writing out the same code over and over, loops allow us to tell computers to repeat a given block of code on its own. One way to give computers these instructions is with a <a href="https://www.codecademy.com/resources/docs/javascript/loops?page_ref=catalog">for loop</a>.</p><p>The typical for loop includes an <em>iterator variable</em> that usually appears in all three expressions. The iterator variable is initialized, checked against the stopping condition, and assigned a new value on each loop iteration. Iterator <a href="https://www.codecademy.com/resources/docs/javascript/variables">variables</a> can have any name, but it’s best practice to use a descriptive variable name.</p><p>A for loop contains three expressions separated by ; inside the parentheses:</p><ol><li>an <em>initialization</em> starts the loop and can also be used to declare the iterator variable.</li><li>a <em>stopping condition</em> is the condition that the iterator variable is evaluated against — if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.</li><li>an <em>iteration statement</em> is used to update the iterator variable on each loop.</li></ol><p>The for loop syntax looks like this:</p><pre>for (let counter = 0; counter &lt; 4; counter++) {<br>  console.log(counter);<br>}</pre><p>In this example, the output would be the following:</p><pre>0<br>1<br>2<br>3</pre><p>Let’s break down the example:</p><ul><li>The initialization is let counter = 0, so the loop will start counting at 0.</li><li>The stopping condition is counter &lt; 4, meaning the loop will run as long as the iterator variable, counter, is less than 4.</li><li>The iteration statement is counter++. This means after each loop, the value of counter will increase by 1. For the first iteration counter will equal 0, for the second iteration counter will equal 1, and so on.</li><li>The code block is inside of the curly braces, console.log(counter), will execute until the condition evaluates to false. The condition will be false when counter is greater than or equal to 4 — the point that the condition becomes false is sometimes called the <em>stop condition</em>.</li></ul><p>This for loop makes it possible to write 0, 1, 2, and 3 programmatically.</p><h3>Looping through Arrays</h3><p>for <a href="https://www.codecademy.com/resources/docs/javascript/loops">loops</a> are very handy for iterating over data structures. For example, we can use a for loop to perform the same operation on each element on an array. <a href="https://www.codecademy.com/resources/docs/javascript/arrays?page_ref=catalog">Arrays</a> hold lists of data, like customer names or product information. Imagine we owned a store and wanted to increase the price of every product in our catalog. That could be a lot of repeating code, but by using a for loop to iterate through the array we could accomplish this task easily.</p><p>To loop through each element in an array, a for loop should use the array’s .length property in its condition.</p><p>Check out the example below to see how for loops iterate on arrays:</p><pre>const animals = [&#39;Grizzly Bear&#39;, &#39;Sloth&#39;, &#39;Sea Lion&#39;];<br>for (let i = 0; i &lt; animals.length; i++){<br>  console.log(animals[i]);<br>}</pre><p>This example would give you the following output:</p><pre>Grizzly Bear<br>Sloth<br>Sea Lion</pre><p>In the loop above, we’ve named our iterator variable i. This is a variable naming convention you’ll see in a lot of loops. When we use i to iterate through arrays we can think of it as being short-hand for the word <strong>i</strong>ndex. Notice how our stopping condition checks that i is less than animals.length. Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1. If we tried to access an element at the index of animals.length we will have gone too far!</p><h3>Nested Loops</h3><p>When we have a loop running inside another loop, we call that a <em>nested loop</em>. One use for a nested for loop is to compare the elements in two <a href="https://www.codecademy.com/resources/docs/javascript/arrays">arrays</a>. For each round of the outer for loop, the inner for loop will run completely.</p><p>Let’s look at an example of a nested for loop:</p><pre>const myArray = [6, 19, 20];<br>const yourArray = [19, 81, 2];<br>for (let i = 0; i &lt; myArray.length; i++) {<br>  for (let j = 0; j &lt; yourArray.length; j++) {<br>    if (myArray[i] === yourArray[j]) {<br>      console.log(&#39;Both arrays have the number: &#39; + yourArray[j]);<br>    }<br>  }<br>}</pre><p>Let’s think about what’s happening in the nested loop in our example. For each element in the outer loop array, myArray, the inner loop will run in its entirety comparing the current element from the outer array, myArray[i], to each element in the inner array, yourArray[j]. When it finds a match, it prints a string to the console.</p><p>Now it’s your turn to write a nested loop!</p><p><strong>Note:</strong> To exit out of an infinite loop in an exercise, <strong>refresh the page</strong> — then fix the code for your loop(s).</p><h3>The While Loop</h3><p>You’re doing great! We’re going to teach you about a different type of loop: the <a href="https://www.codecademy.com/resources/docs/javascript/loops?page_ref=catalog">while loop</a>. To start, let’s convert a for loop into a while loop:</p><pre>// A for loop that prints 1, 2, and 3<br>for (let counterOne = 1; counterOne &lt; 4; counterOne++){<br>  console.log(counterOne);<br>}<br><br>// A while loop that prints 1, 2, and 3<br>let counterTwo = 1;<br>while (counterTwo &lt; 4) {<br>  console.log(counterTwo);<br>  counterTwo++;<br>}</pre><p>Let’s break down what’s happening with our while loop syntax:</p><ul><li>The counterTwo variable is declared before the loop. We can access it inside our while loop since it’s in the global scope.</li><li>We start our loop with the keyword while followed by our stopping condition, or <em>test condition</em>. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop.</li><li>Next, we have our loop’s code block which prints counterTwo to the console and increments counterTwo.</li></ul><p>What would happen if we didn’t increment counterTwo inside our block? If we didn’t include this, counterTwo would always have its initial value, 1. That would mean the testing condition counterTwo &lt; 4 would always evaluate to true and our loop would never stop running! Remember, this is called an <em>infinite loop</em> and it’s something we always want to <strong>avoid</strong>. Infinite loops can take up all of your computer’s processing power potentially freezing your computer.</p><p>So you may be wondering when to use a while loop! The syntax of a while loop is ideal when we don’t know in advance how many times the loop should run. Think of eating like a while loop: when you start taking bites, you don’t know the exact number you’ll need to become full. Rather you’ll eat while you’re hungry. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice.</p><h3>Do…While Statements</h3><p>In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in.</p><p>A <a href="https://www.codecademy.com/resources/docs/javascript/loops?page_ref=catalog">do...while</a> statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this:</p><pre>let countString = &#39;&#39;;<br>let i = 0;<br><br>do {<br>  countString = countString + i;<br>  i++;<br>} while (i &lt; 5);<br><br>console.log(countString);</pre><p>In this example, the code block makes changes to the countString variable by appending the string form of the i variable to it. First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.</p><p>Note that the while and do...while loop are different! Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.</p><pre>const firstMessage = &#39;I will print!&#39;;<br>const secondMessage = &#39;I will not print!&#39;; <br><br>// A do while with a stopping condition that evaluates to false<br>do {<br> console.log(firstMessage)<br>} while (true === false);<br><br>// A while loop with a stopping condition that evaluates to false<br>while (true === false){<br>  console.log(secondMessage)<br>};</pre><p><strong>Note:</strong> To exit out of an infinite loop in an exercise, <strong>refresh the page</strong> — then fix the code for your loop(s).</p><h3>The break Keyword</h3><p>Imagine we’re looking to adopt a dog. We plan to go to the shelter every day for a year and then give up. But what if we meet our dream dog on day 65? We don’t want to keep going to the shelter for the next 300 days just because our original plan was to go for a whole year. In our code, when we want to stop a loop from continuing to execute even though the original stopping condition we wrote for our loop hasn’t been met, we can use the keyword break.</p><p>The <a href="https://www.codecademy.com/resources/docs/javascript/loops?page_ref=catalog">break keyword</a> allows programs to “break” out of the loop from within the loop’s block.</p><p>Let’s check out the syntax of a break keyword:</p><pre>for (let i = 0; i &lt; 99; i++) {<br>  if (i &gt; 2 ) {<br>     break;<br>  }<br>  console.log(&#39;Banana.&#39;);<br>}<br><br>console.log(&#39;Orange you glad I broke out the loop!&#39;);</pre><p>This is the output for the above code:</p><pre>Banana.<br>Banana.<br>Banana.<br>Orange you glad I broke out the loop!</pre><p>break <a href="https://www.codecademy.com/resources/docs/javascript/statements">statements</a> can be especially helpful when we’re looping through large data structures! With breaks, we can add test conditions besides the stopping condition, and exit the loop when they’re met.</p><h3>Review</h3><p>Great job! In this lesson, we learned how to write cleaner code with <a href="https://www.codecademy.com/resources/docs/javascript/loops">loops</a>. You now know:</p><ul><li>Loops perform repetitive actions so we don’t have to code that process manually every time.</li><li>How to write for loops with an iterator variable that increments or decrements</li><li>How to use a for loop to iterate through an array</li><li>A nested for loop is a loop inside another loop</li><li>while loops allow for different types of stopping conditions</li><li>Stopping conditions are crucial for avoiding infinite loops.</li><li>do...while loops run code at least once— only checking the stopping condition after the first execution</li><li>The break keyword allows programs to leave a loop during the execution of its block</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzkBpmPUDiAR8Y2PwARu-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeTRhP1lpKJEvYiV-oFWJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQsaNJAQZLLHU9fDr--IRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTYzxB3NzMzHiS0T1TBbvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njVSnLMuuNu7V4f4iFZulw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgCNjMnFaw5zoySkYaTFBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkeNSuFVO5KC9Q0TmebqLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5u6hH0b8zBZYiz94ECFVQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3361818d1e75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS — ARRAYS]]></title>
            <link>https://medium.com/@jasurbek.go.dev/js-arrays-5273aa6b527a?source=rss-d12b6a49500d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5273aa6b527a</guid>
            <category><![CDATA[formes]]></category>
            <dc:creator><![CDATA[perfectogo]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 18:26:01 GMT</pubDate>
            <atom:updated>2023-08-19T18:26:01.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS — ARRAYS</h3><h3>Arrays</h3><p>Organizing and storing data is a foundational concept of programming.</p><p>One way we organize data in real life is by making lists. Let’s make one here:</p><pre>New Year&#39;s Resolutions:<br><br>1. Keep a journal <br>2. Take a falconry class<br>3. Learn to juggle</pre><p>Let’s now write this list in JavaScript, as an <em>array</em>:</p><pre>let newYearsResolutions = [&#39;Keep a journal&#39;, &#39;Take a falconry class&#39;, &#39;Learn to juggle&#39;];</pre><p><a href="https://www.codecademy.com/resources/docs/javascript/arrays?page_ref=catalog">Arrays</a> are JavaScript’s way of making lists. Arrays can store any <a href="https://www.codecademy.com/resources/docs/javascript/data-types">data types</a> (including <a href="https://www.codecademy.com/resources/docs/javascript/strings">strings</a>, numbers, and booleans). Like lists, arrays are ordered, meaning each item has a numbered position.</p><p>Here’s an array of the concepts we’ll cover:</p><pre>let concepts = [&#39;creating arrays&#39;, &#39;array structures&#39;, &#39;array manipulation&#39;];</pre><h3>Create an Array</h3><p>One way we can create an array is to use an <em>array literal</em>. An array literal creates an array by wrapping items in square brackets []. Remember from the previous exercise, arrays can store any data type — we can have an array that holds all the same data types or an array that holds different data types.</p><p>Let’s take a closer look at the syntax in the array example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*7y6_UdhH4cGvMVZyFXA4pw.png" /></figure><ul><li>The array is represented by the square brackets [] and the content inside.</li><li>Each content item inside an array is called an <em>element</em>.</li><li>There are three different elements inside the array.</li><li>Each element inside the array is a different data type.</li></ul><p>We can also save an array to a variable. You may have noticed we did this in the previous exercise:</p><pre>let newYearsResolutions = [&#39;Keep a journal&#39;, &#39;Take a falconry class&#39;, &#39;Learn to juggle&#39;];</pre><h3>Accessing Elements</h3><p>Each element in an array has a numbered position known as its <em>index</em>. We can access individual items using their index, which is similar to referencing an item in a list based on the item’s position.</p><p>Arrays in JavaScript are <em>zero-indexed</em>, meaning the positions start counting from 0 rather than 1. Therefore, the first item in an array will be at position 0. Let’s see how we could access an element in an array:</p><p>In the code snippet above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmMQfni0UUf4ygNb6Itwzw.png" /></figure><ul><li>cities is an array that has three elements.</li><li>We’re using bracket notation, [] with the index after the name of the array to access the element.</li><li>cities[0] will access the element at index 0 in the array cities. You can think of cities[0] as accessing the space in memory that holds the string &#39;New York&#39;.</li></ul><p>You can also access individual characters in a string using bracket notation and the index. For instance, you can write:</p><pre>const hello = &#39;Hello World&#39;;<br>console.log(hello[6]);<br>// Output: W</pre><h3>Update Elements</h3><p>In the previous exercise, you learned how to access elements inside an array or a string by using an index. Once you have access to an element in an array, you can update its value.</p><pre>let seasons = [&#39;Winter&#39;, &#39;Spring&#39;, &#39;Summer&#39;, &#39;Fall&#39;];<br><br>seasons[3] = &#39;Autumn&#39;;<br>console.log(seasons); <br>//Output: [&#39;Winter&#39;, &#39;Spring&#39;, &#39;Summer&#39;, &#39;Autumn&#39;]</pre><p>In the example above, the seasons array contained the names of the four seasons.</p><p>However, we decided that we preferred to say &#39;Autumn&#39; instead of &#39;Fall&#39;.</p><p>The line, seasons[3] = &#39;Autumn&#39;; tells our program to change the item at index 3 of the seasons array to be &#39;Autumn&#39; instead of what is already there.</p><h3>Arrays with let and const</h3><p>You may recall that you can declare <a href="https://www.codecademy.com/resources/docs/javascript/variables?page_ref=catalog">variables</a> with both the let and const keywords. Variables declared with let can be reassigned.</p><p>Variables declared with the const keyword cannot be reassigned. However, elements in an array declared with const remain mutable. Meaning that we can change the contents of a const array, but cannot reassign a new array or a different value.</p><p>The instructions below will illustrate this concept more clearly. Pay close attention to the similarities and differences between the condiments array and the utensils array as you complete the steps.</p><h3>The .length property</h3><p>One of an array’s built-in properties is length and it returns the number of items in the array. We access the <a href="https://www.codecademy.com/resources/docs/javascript/strings/length?page_ref=catalog">.length</a> property just like we do with strings. Check the example below:</p><pre>const newYearsResolutions = [&#39;Keep a journal&#39;, &#39;Take a falconry class&#39;];<br><br>console.log(newYearsResolutions.length);<br>// Output: 2</pre><p>In the example above, we log newYearsResolutions.length to the console using the following steps:</p><ul><li>We use <em>dot notation</em>, chaining a period with the property name to the array, to access the length property of the newYearsResolutions array.</li><li>Then we log the length of newYearsResolution to the console.</li><li>Since newYearsResolution has two elements, 2 would be logged to the console.</li></ul><p>When we want to know how many elements are in an array, we can access the .length property.</p><h3>The .push() Method</h3><p>Let’s learn about some built-in JavaScript <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> that make working with arrays easier. These methods are specifically called on arrays to make common tasks, like adding and removing elements, more straightforward.</p><p>One method, <a href="https://www.codecademy.com/resources/docs/javascript/arrays/push?page_ref=catalog">.push(),</a> allows us to add items to the end of an array. Here is an example of how this is used:</p><pre>const itemTracker = [&#39;item 0&#39;, &#39;item 1&#39;, &#39;item 2&#39;];<br><br>itemTracker.push(&#39;item 3&#39;, &#39;item 4&#39;);<br><br>console.log(itemTracker); <br>// Output: [&#39;item 0&#39;, &#39;item 1&#39;, &#39;item 2&#39;, &#39;item 3&#39;, &#39;item 4&#39;];</pre><p>So, how does .push() work?</p><ul><li>We access the push method by using dot notation, connecting push to itemTracker with a period.</li><li>Then we call it like a function. That’s because .push() is a function and one that JavaScript allows us to use right on an array.</li><li>.push() can take a single argument or multiple arguments separated by commas. In this case, we’re adding two elements: &#39;item 3&#39; and &#39;item 4&#39; to itemTracker.</li><li>Notice that .push() changes, or <em>mutates</em>, itemTracker. You might also see .push() referred to as a <em>destructive</em> array method since it changes the initial array.</li></ul><p>If you’re looking for a method that will mutate an array by adding elements to it, then .push() is the method for you!</p><h3>The .pop() Method</h3><p>Another array method, <a href="https://www.codecademy.com/resources/docs/javascript/arrays/pop?page_ref=catalog">.pop()</a>, removes the last item of an array.</p><pre>const newItemTracker = [&#39;item 0&#39;, &#39;item 1&#39;, &#39;item 2&#39;];<br><br>const removed = newItemTracker.pop();<br><br>console.log(newItemTracker); <br>// Output: [ &#39;item 0&#39;, &#39;item 1&#39; ]<br>console.log(removed);<br>// Output: item 2</pre><ul><li>In the example above, calling .pop() on the newItemTracker array removed item 2 from the end.</li><li>.pop() does not take any arguments, it simply removes the last element of newItemTracker.</li><li>.pop() returns the value of the last element. In the example, we store the returned value in a variable removed to be used for later.</li><li>.pop() is a method that mutates the initial array.</li></ul><p>When you need to mutate an array by removing the last element, use .pop().</p><h3>More Array Methods</h3><p>There are many more array <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a> than just <a href="https://www.codecademy.com/resources/docs/javascript/arrays/push">.push()</a> and <a href="https://www.codecademy.com/resources/docs/javascript/arrays/pop">.pop()</a>. You can read about these array methods on the Docs entry for <a href="https://www.codecademy.com/resources/docs/javascript/arrays">JavaScript Arrays</a>.</p><p>.pop() and .push() mutate the array on which they’re called. However, there are times that we don’t want to mutate the original array and we can use non-mutating array methods. Be sure to check the Docs to understand the behavior of the method you are using.</p><p>Some arrays methods that are available to JavaScript developers include: <a href="https://www.codecademy.com/resources/docs/javascript/arrays/join">.join()</a>, .slice(), <a href="https://www.codecademy.com/resources/docs/javascript/arrays/splice">.splice()</a>, <a href="https://www.codecademy.com/resources/docs/javascript/arrays/shift">.shift()</a>, <a href="https://www.codecademy.com/resources/docs/javascript/arrays/unshift">.unshift()</a>, and .concat() amongst many others. Using these built-in methods makes it easier to do some common tasks when working with arrays.</p><p>Below, we will explore some methods that we have not learned yet. We will use these methods to edit a grocery list. As you complete the steps, you can consult the <a href="https://www.codecademy.com/resources/docs/javascript">Codecademy Docs</a> to learn what each method does!</p><h3>Arrays and Functions</h3><p>Throughout the lesson we went over arrays being mutable, or changeable. Well what happens if we try to change an array inside a function? Does the array keep the change after the function call or is it scoped to inside the function?</p><p>Take a look at the following example where we call <a href="https://www.codecademy.com/resources/docs/javascript/arrays/push">.push()</a> on an array inside a function. Recall, the .push() method mutates, or changes, an array:</p><pre>const flowers = [&#39;peony&#39;, &#39;daffodil&#39;, &#39;marigold&#39;];<br><br>function addFlower(arr) {<br>  arr.push(&#39;lily&#39;);<br>}<br><br>addFlower(flowers);<br><br>console.log(flowers); // Output: [&#39;peony&#39;, &#39;daffodil&#39;, &#39;marigold&#39;, &#39;lily&#39;]</pre><p>Let’s go over what happened in the example:</p><ul><li>The flowers array that has 3 elements.</li><li>The function addFlower() has a parameter of arr uses .push() to add a &#39;lily&#39; element into arr.</li><li>We call addFlower() with an argument of flowers which will execute the code inside addFlower.</li><li>We check the value of flowers and it now includes the &#39;lily&#39; element! The array was mutated!</li></ul><p>So when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as <em>pass-by-reference</em> since what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.</p><h3>Nested Arrays</h3><p>Earlier we mentioned that <a href="https://www.codecademy.com/resources/docs/javascript/arrays">arrays</a> can store other arrays. When an array contains another array it is known as a <em>nested array</em>. Examine the example below:</p><pre>const nestedArr = [[1], [2, 3]];</pre><p>To access the nested arrays we can use bracket notation with the index value, just like we did to access any other element:</p><pre>const nestedArr = [[1], [2, 3]];<br><br>console.log(nestedArr[1]); // Output: [2, 3]</pre><p>Notice that nestedArr[1] will grab the element in index 1 which is the array [2, 3]. Then, if we wanted to access the elements within the nested array we can <em>chain</em>, or add on, more bracket notation with index values.</p><pre>const nestedArr = [[1], [2, 3]];<br>console.log(nestedArr[1]); // Output: [2, 3]<br>console.log(nestedArr[1][0]); // Output: 2</pre><p>In the second console.log() statement, we have two bracket notations chained to nestedArr. We know that nestedArr[1] is the array [2, 3]. Then to grab the first element from that array, we use nestedArr[1][0] and we get the value of 2</p><h3>Review Arrays</h3><p>Nice work! In this lesson, we learned these concepts regarding arrays:</p><ul><li>Arrays are lists that store data in JavaScript.</li><li>Arrays are created with brackets [].</li><li>Each item inside of an array is at a numbered position, or index, starting at 0.</li><li>We can access one item in an array using its index, with syntax like: myArray[0].</li><li>We can also change an item in an array using its index, with syntax like myArray[0] = &#39;new string&#39;;</li><li>Arrays have a length property, which allows you to see how many items are in an array.</li><li>Arrays have their own <a href="https://www.codecademy.com/resources/docs/javascript/methods">methods</a>, including <a href="https://www.codecademy.com/resources/docs/javascript/arrays/push">.push()</a> and <a href="https://www.codecademy.com/resources/docs/javascript/arrays/pop">.pop()</a>, which add and remove items from an array, respectively.</li><li>Arrays have many methods that perform different tasks, such as .slice() and <a href="https://www.codecademy.com/resources/docs/javascript/arrays/shift">.shift()</a>, you can find documentation at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Mozilla Developer Network</a> website.</li><li>Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.</li><li><a href="https://www.codecademy.com/resources/docs/javascript/variables">Variables</a> that contain arrays can be declared with let or const. Even when declared with const, arrays are still mutable. However, a variable declared with const cannot be reassigned.</li><li>Arrays mutated inside of a function will keep that change even outside the function.</li><li>Arrays can be nested inside other arrays.</li><li>To access elements in nested arrays chain indices using bracket notation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLxlI--iuZEwMiVcR4zn-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFTO5DoGAmB0qEwL_DGf_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ms4zMGMLhqQ_ME2VTqgvNg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5273aa6b527a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>