<?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 Femi Majek on Medium]]></title>
        <description><![CDATA[Stories by Femi Majek on Medium]]></description>
        <link>https://medium.com/@olaoluwaphemy?source=rss-a52134ba5b65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XCMK11GRPpE71C2E4k1Zqg.jpeg</url>
            <title>Stories by Femi Majek on Medium</title>
            <link>https://medium.com/@olaoluwaphemy?source=rss-a52134ba5b65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:58:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olaoluwaphemy/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[Pagination in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/pagination-in-javascript-7bcde99b3add?source=rss-a52134ba5b65------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcde99b3add</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Femi Majek]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 14:17:17 GMT</pubDate>
            <atom:updated>2023-12-11T14:17:17.676Z</atom:updated>
            <content:encoded><![CDATA[<h4>A complete step-by-step practical guide on how you can implement pagination using vanilla JavaScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZN8F5fUGozsr94popbdaQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@roman34nov?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Roman Trifonov</a> on <a href="https://unsplash.com/photos/opened-book-on-brown-wooden-surface-67rnodKzsRQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this article, we’ll be implementing a pretty common concept in JavaScript called “Pagination”. It’s a technique that allows for content to be divided into smaller, more manageable chunks or pages. It allows users to navigate through pages of data instead of one long page of scrollable data. For this lesson, we’ll be making use of a REST API that contains data about world countries. Attached in the resources section, is the REST API URL and a link to its documentation.</p><h3>Prerequisites</h3><ul><li>Knowledge of HTML, CSS, and basic JavaScript</li><li>Familiarity with making AJAX calls</li><li>Familiarity with consuming promises using async/await</li><li>Basic understanding of event delegation &amp; DOM traversing.</li></ul><h3>Resources</h3><p>COUNTRIES API-URL: <a href="https://restcountries.com/v3.1/all">https://restcountries.com/v3.1/all</a></p><p>API Documentation: <a href="https://restcountries.com/">https://restcountries.com/</a></p><p>Before proceeding, It’s advised to take a quick/careful look at the API and its documentation, to avoid any form of confusion at any point in the rest of the article.</p><h3>Step 1: Quick review of the HTML structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ob636vEheDobzWx3TdSj4A.png" /></figure><p>The HTML structure is quite straightforward, it’s made up of an unordered list with a class “container”, and in this unordered list we have the first item which is a div with a class list-container, it’s inside this list-container div we’ll have a list of each of the countries we’ll be rendering in the browser. The second item of the unordered list is another div with the class pagination, this div will be responsible for housing the pagination buttons when they’re rendered in the browser. Note that the markup for the list items and the pagination buttons themselves are “commented out”, this is because later on, we’ll be inserting them dynamically into the DOM using JavaScript. For more on the HTML structure alongside its complete styling, you can visit a codepen link to the source code <a href="https://codepen.io/Phemy-M/pen/rNPRVQG">here</a>.</p><h3>Step 2: Getting the countries’ data</h3><p>Moving on, we’ll be getting the countries’ data by making an AJAX call to the provided API URL, using the fetch method inside an async function that we’ll call fetchJSON().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*twA16YKOvGlrIvTT" /></figure><p>As seen above, an AJAX call was made to the provided API URL using the fetch method inside the fetchJSON() async function. The resulting promise returned by the fetch method is consumed using await, and the response is stored in the res variable. Calling the json() method on the res variable also returns a promise which is in turn consumed using await and the resulting data is stored in the data variable. A look at our data variable in the console shows an array containing 250 objects, it’s from these individual objects we’ll get the necessary data needed to populate our UI(data such as the country name, capital, etc.). Before proceeding please do well to take a quick look at how the properties in these data objects are structured.</p><h3><strong>Step 3: rendering each country list</strong></h3><p>Before we move on, let’s look at some of the things we need to implement before rendering the country lists. Before rendering we need to:</p><ul><li>Determine the number of content(country lists) we want to render per page and also calculate the total number of pages.</li><li>Come up with a formula that determines what part of the complete data we want to render for each page.</li><li>Generate HTML markup for the data part to be rendered/inserted into the DOM.</li><li>Finally, we’ll need to generate the HTML markup for the pagination buttons and determine the logic needed to render the buttons in different scenarios.</li></ul><p>Now that we’ve established a list of to-do’s, we’ll be implementing all of this in a function called renderCountryLists(), this function will take an argument curPage, which will have a value of the page currently being viewed in the browser.</p><p>But before we proceed, at this point, it’s a great idea to have the variables relevant to our app development pre-selected and also create a state object. The state object will be responsible for storing data relevant to the browser/DOM, such as the fetched countries’ data, the current page in view, and the number of content we’ll be rendering per page.</p><pre>&quot;use strict&quot;;<br>const container = document.querySelector(&quot;.container&quot;);<br>const mainContainer = document.querySelector(&quot;.list-container&quot;);<br>const pagination = document.querySelector(&quot;.pagination&quot;);<br><br>const state = {<br>countriesData: [],<br>currentPage: 1,<br>contentPerPage: 10,<br>};</pre><p>As shown the state object contains the properties countriesData, currentPage, and contentPerPage. The countriesData and currentPage properties have their values initialized to an empty array and one respectively. Later on, their values will get updated while contentPerPage will have the constant value of ten(more on this later).</p><h3>Determining the number of pages</h3><p>The number of pages would be determined based on the number of countries we want to be rendered per page, for the case of this lesson we’ll be rendering ten countries per page(we have the value stored in the state as contentPerPage, we’ll also be storing the number of pages in our state object as numPages later on). Below is an illustration of how the number of pages is calculated:</p><pre>const numPages = Math.ceil(state.countriesData.length / state.contentPerPage);<br>// Math.ceil() is used to round the number up in case a fraction is the value returned from the division.</pre><p>The number of pages is calculated by dividing the length of the data array gotten from the API(stored in the state object as countriesData) by the number of content per page(stored in the state object as contentPerPage). However, for this to work we first need to update the value of the countriesData property inside the state object, in our fetchJSON() function.</p><pre>const fetchJSON = async function () {<br>  const res = await fetch(&quot;https://restcountries.com/v3.1/all&quot;);<br>  const data = await res.json();<br><br>  state.countriesData = data;<br>// here the countriesData property is updated <br>};<br></pre><h3>Determining part of the data to render</h3><pre>const renderCountryLists = function (curPage = state.currentPage) {<br>  const numPages = Math.ceil(state.countriesData.length / state.contentPerPage);<br>state.numPages = numPages; // a new property numPages is added to the state object<br><br>  const start = (curPage - 1) * state.contentPerPage;<br>  const end = curPage * state.contentPerPage;<br>};</pre><p>As said earlier, we now have the renderCountryLists() function and in it, we calculate the total number of pages we’ll be rendering, the number of pages is then stored in the state as numPages. In the renderCountryLists() we also have two variables start and end which will be the values responsible for extracting(slicing out) the part of the countries’ data that we’ll be rendering in the DOM. start is calculated by subtracting one from the curPage variable(remember curPage holds the value of the page currently being viewed in the DOM by the user) and multiplied by the number of content per page. end is calculated by multiplying the curPage with the number of content per page, the start variable determines where slicing of the countries’ data will begin and end as the name suggests determines where slicing will end/stop. The curPage is given a default value of one, which is the initial value of the currentPage property in the state object(it’s initialized to one because page one will be the default/initial page rendered as soon as the script runs).</p><p>The data to be rendered is thus extracted as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d98hR4yXxYCmKvNp" /></figure><p><strong>NOTE:</strong> At this point of development for us to be able to illustrate and view how our needed data will be extracted, the renderCountryLists() has to be an async function, because the data from which we’ll be extracting needs to arrive first before extraction/slicing takes place.</p><p>So as shown, on logging our start and end variables to the console we get the values 0 and 10, which are the initial values that’ll determine what part of the complete countries’ data is sliced. Using the slice() method and setting its arguments to the start and end variables respectively we get the slice/part of the complete array to be rendered, the resulting array is then stored in the dataToRender variable. And since arrays are zero-based we get the length of the dataToRender array as ten which is exactly the number of the content we want to be rendered per page (please recall that the slice method does not include the data that matches the index specified in its second argument i.e. it stops extracting/slicing right before the index specified in the second argument). Let’s now move on to dynamically generating HTML markup that we’ll be inserting in the DOM.</p><h3>Generating HTML for data to be rendered</h3><p>For each of the 10 countries to be rendered per page, we’ll need a custom markup that would contain information specific and relevant to these countries, these pieces of information would be gotten from their respective corresponding objects. To achieve this we’ll be using a function that’ll be called generateMarkup(), which will be a function that returns a markup string of all ten countries combined, by using the array map() and join() methods.</p><pre>const generateMarkup = function (data) {<br>return data<br>.map((obj) =&gt; {<br>   return `<br>      &lt;li&gt;<br>          &lt;p class=&quot;name&quot;&gt;${obj.name.common}&lt;/p&gt;<br>          &lt;p class=&quot;capital&quot;&gt;${obj.capital ? obj.capital[0] : &quot;&quot;}&lt;/p&gt;<br>          &lt;p&gt;${(obj.population / 1000000).toFixed(2)} million&lt;/p&gt;<br>        &lt;div class=&quot;flag&quot;&gt;<br>          &lt;img src=&quot;${obj.flags.png}&quot; alt=&quot;country flag&quot; /&gt;<br>        &lt;/div&gt;<br>      &lt;/li&gt;<br>`;<br>})<br>.join(&quot;&quot;);<br>};</pre><p>As seen above, the generateMarkup() function takes in an argument data, which will be an array of the ten country objects to be rendered in the current view. The function returns a single string of markup for all ten countries by first calling the map() method on the data array and then calling the join() method on the resulting array from the map() method. Before proceeding, please do well to examine the markup closely and the generateMarkup() function carefully.</p><p><strong>NOTE: </strong>the paragraph element(&lt;p&gt;) with class capital has its content set conditionally, this is because it was discovered in the course of development that some of the countries’ objects didn’t have a “capital” property set in them. So using a ternary operator, the paragraph content is set to the country capital, if the capital property is present in the object in the current iteration or set to an empty string if otherwise.</p><p>Now the next step is to insert this newly generated markup in the DOM, this step, including calling the function responsible for generating the markup, will be carried out in the renderCountryLists() function.</p><pre>const renderCountryLists = function (curPage = state.curPage) {<br>  const numPages = Math.ceil(state.countriesData.length / state.contentPerPage);<br>  state.numPages = numPages;<br><br>  const start = (curPage - 1) * state.contentPerPage;<br>  const end = curPage * state.contentPerPage;<br><br>  const dataToRender = state.countriesData.slice(start, end)<br>  const markup = generateMarkup(dataToRender);<br><br>  mainContainer.innerHTML = &quot;&quot;;<br>  mainContainer.insertAdjacentHTML(&quot;beforeend&quot;, markup);<br>};</pre><p>The generateMarkup() function is called with the dataToRender variable and the resulting markup is stored in the markup variable. This markup is then dynamically inserted into the DOM using the insertAdjacentHTML() method. The method is called on the container that’ll be housing the country lists(in our case the container is already preselected and stored in the mainContainer variable), the method takes two arguments the first is “beforeend” which specifies the position where the markup is to be inserted in the container and the other argument being the markup itself. Also notice how the mainContainer variable is first cleared by setting its innerHTML to an empty string, before inserting the new markup. This ensures that the countries’ list container is cleared anytime a new rendering is set to take place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*klfIkWEfxkkYtsDz" /></figure><p>And now we have our very first set of data rendered to the DOM, and as seen the list of countries is exactly ten, each country rendered with its respective relevant data. However, the data rendered is only the first page of the complete data received from the API, hence, we now need a way to switch between the rest of the pages. To achieve this, we’ll now also need to render the pagination buttons and connect each page rendering to clicks on either of two buttons(the previous and next buttons).</p><h3>Rendering Pagination buttons</h3><p>To render the pagination buttons, we also need to develop an HTML markup for the buttons and a logic that’ll be responsible for which button is rendered depending on what part of the data(page) is currently being viewed in the DOM. Now let’s look at some of the possible viewing scenarios that we could expect in this case:</p><ul><li>The first case is when the user is on the first page of view, in this case, we only need one button rendered, which is a button that takes the current view to the next page when clicked.</li><li>The second scenario is when the user is on some other page(i.e. all pages between the first and last), in this case, we need to render two buttons the left button which takes the view to the previous page on click and the right button which takes the view to the next page on click.</li><li>Finally, the last scenario is when the user is on the last page. In this case, we only need to render one button that’ll take the current page in view to the previous page on click.</li></ul><p>Now that this has been well established, let’s translate all of it into code. We’ll be creating a new function for this, which will be called every time a new page is rendered. We’ll name this function generateButtons() and it’ll take an argument curPage which will be the value of the page currently being viewed in the DOM.</p><pre>const generateButtons = function (curPage) {<br>  if (curPage === 1)<br>    return `<br>        &lt;div class=&quot;button&quot;&gt;<br>          &lt;button class=&quot;btn right&quot;&gt;&lt;span&gt;next&lt;span/&gt;&lt;/button&gt;<br>        &lt;/div&gt;<br>  `;<br>  if (curPage !== 1 &amp;&amp; curPage &lt; state.numPages)<br>    return `<br>        &lt;div class=&quot;button&quot;&gt;<br>          &lt;button class=&quot;btn left&quot;&gt;&lt;span&gt;prev&lt;span/&gt;&lt;/button&gt;<br>          &lt;button class=&quot;btn right&quot;&gt;&lt;span&gt;next&lt;span/&gt;&lt;/button&gt;<br>        &lt;/div&gt;<br>  `;<br>  if (curPage === state.numPages)<br>    return `<br>      &lt;div class=&quot;button&quot;&gt;<br>        &lt;button class=&quot;btn left&quot;&gt;&lt;span&gt;prev&lt;span/&gt;&lt;/button&gt;<br>      &lt;/div&gt;<br>  `;<br>};</pre><p>It’s now at this point that we’ll be making use of the numPages property stored in the state object, recall the property stores the number of total pages we want for our data. Moving on, using multiple “if” statements we set a condition for what button(s) markup to return based on the page in the current view. In the case of the current page being equal to one(i.e. curPage === 1) a markup of the next button is returned, for a case of pages in between the first and last (i.e.curPage !== 1 &amp;&amp; curPage &lt; numPages) a markup of both the next and previous buttons are returned. Finally, in the case of the current page being equal to the last page (i.e. curPage === numPages), a markup of only the previous button is returned.</p><p>Now that these markups have been properly set up and tied to their relevant conditions, we need to dynamically insert them into the DOM. For this, we’ll be creating another function renderButtons() which will be responsible for calling the generateButtons() function and inserting the resulting markup into the DOM, it’ll also take an argument of the current page(curPage).</p><pre>const renderButtons = function (curPage) {<br>  const markup = generateButtons(curPage);<br>  pagination.innerHTML = &quot;&quot;;<br>  pagination.insertAdjacentHTML(&quot;afterbegin&quot;, markup);<br>};</pre><p>As shown above, the renderButtons() takes care of generating the pagination buttons, clears the pagination container where it’ll be rendered, and inserts the newly generated button(s) into the DOM using the insertAdjacentHTML() that’s called on the pagination container.</p><p>Now when do we want to render the pagination buttons? Well, you guessed right, the pagination buttons will be rendered as soon as the first set of data to be rendered in the DOM arrives, likewise every time a new page is rendered in the DOM. In other words, we’ll be calling the renderButtons() function right in the renderCountriesList() function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RfEPucSMFV8mQ5n0" /></figure><p>Great, we now have our first pagination button rendered in the DOM and as expected it’s the right button that indicates navigation to the next page. But at this point, it’s non-functional, and so this brings us to the implementation part of the pagination buttons. We now need to listen for clicks on the button(s) such that new country lists and new pagination buttons are rendered each time either of the navigation buttons is clicked. To implement this we will be using “Event Delegation” i.e. we’ll be attaching an event listener to a parent element of the pagination buttons(we do this because at runtime there is/are no button(s) to which we can attach the event listener since the buttons are dynamically generated and inserted into the DOM).</p><h4>Step 4: re-rendering each country list and pagination buttons</h4><p>In this step, we’ll be updating our UI whenever a click is made on any of the navigation buttons, in other words, we’ll re-render both the countries’ list and pagination buttons by calling the renderCountriesList() function each time there’s a click on any one of the buttons. For this to work we’ll need a way of getting the page number of the current view from the DOM, and we can achieve this by using a special “data-” attribute available to HTML elements which allows us to store data relevant to the DOM, that we can access from our JavaScript code using the “dataset” property. Hence, we need to make a few changes to our pagination buttons’ HTML markup in the generateButtons() function</p><pre>const generateButtons = function (curPage) {<br>  const numPages = Math.ceil(state.countriesData.length / state.contentPerPage);<br>    if (curPage === 1)<br>      return `<br>          &lt;div class=&quot;button&quot;&gt;<br>            &lt;button class=&quot;btn right&quot; data-page=&quot;${<br>            curPage + 1<br>            }&quot;&gt;&lt;span&gt;next&lt;span/&gt; ${curPage + 1}&lt;/button&gt;<br>          &lt;/div&gt;<br>  `;<br>    if (curPage !== 1 &amp;&amp; curPage &lt; state.numPages)<br>      return `<br>          &lt;div class=&quot;button&quot;&gt;<br>            &lt;button class=&quot;btn left&quot; data-page=&quot;${<br>              curPage - 1<br>             }&quot;&gt;&lt;span&gt;prev&lt;span/&gt; ${curPage - 1}&lt;/button&gt;<br>            &lt;button class=&quot;btn right&quot; data-page=&quot;${<br>              curPage + 1<br>             }&quot;&gt;&lt;span&gt;next&lt;span/&gt; ${curPage + 1}&lt;/button&gt;<br>          &lt;/div&gt;<br>  `;<br>    if (curPage === state.numPages)<br>      return `<br>          &lt;div class=&quot;button&quot;&gt;<br>            &lt;button class=&quot;btn left&quot; data-page=&quot;${curPage - 1}&quot;&gt;&lt;span&gt;prev&lt;span/&gt; ${<br>              curPage - 1<br>            }&lt;/button&gt;<br>          &lt;/div&gt;<br>  `;<br>};</pre><p>As shown we have now added a new data attribute to all the possible markups of the pagination buttons. The attribute data-page was set on the navigation buttons themselves, and what this attribute will be responsible for is to store the value of the next/previous page to the page currently being viewed in the DOM, so we can access it in our handler function whenever there’s a click on either button. The value also gets updated as clicks are made on the buttons i.e. clicking on the button marked “next” the value of its data-page attribute gets set to curPage + 1(because we want the next page when the button marked “next” is clicked and that translates to the current page plus one) and clicking on the button marked “prev” gets the value of its data-page attribute set to curPage-1(because we want the previous page when the button marked “prev” is clicked and that translates to the current page minus one). We can then use this value to call the renderCountriesList() function.</p><pre>container.addEventListener(&quot;click&quot;, function (e) {<br>  const btn = e.target.closest(&quot;.btn&quot;);<br><br>  if (!btn) return;<br><br>  const curPage = btn.dataset.page;<br>  state.currentPage = +curPage<br><br>  renderCountryLists(state.currentPage);<br>});</pre><p>We add an event listener to the container which is a parent to the pagination buttons, and on calling the closest() method on e.target(e.target represents the precise element clicked inside the container), we search for the element with class btn(the closest() method looks up the DOM for the closest parent element with the specified class name, in this case, btn), however the closest() method returns null if the clicked element doesn’t contain the class btn, and so to prevent errors, a guard clause is set for our handler function to return early if btn is null. This is done so we only register clicks on the buttons themselves and not other parts of the container.</p><p>With that out of the way, we’re now able to get the value of the page we want to be rendered through the dataset property on btn(like this btn.dataset.page) and the value is stored in the curPage variable. The currentPage property in our “state” object is also updated by setting its value to the curPage variable. Finally, the renderCountryLists() is called with the newly updated current page value stored in the state object i.e. state.currentPage. With these done our app becomes fully functional.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe6sBYpl0chY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De6sBYpl0chY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe6sBYpl0chY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5029435d7435d0e1f6d0b2143bb65529/href">https://medium.com/media/5029435d7435d0e1f6d0b2143bb65529/href</a></iframe><p>And as shown our app is now fully functional and paginated. Hence, we can now move between pages by clicking either of the “next” or “prev” buttons.</p><p>But before wrapping up the article let’s make a final adjustment by refactoring our code a little bit. Recall earlier in the article it was mentioned that the renderCountryLists() function doesn’t have to be an async function, so to fix this we’ll simply create an initializer function that’ll be called init() this function will be an async function that’ll get called immediately i.e. as soon as the script loads and it would in turn, be responsible for calling both the fetchJSON() and renderCountryLists() functions.</p><pre>const init = async function () {<br>  await fetchJSON();<br>  renderCountryLists();<br>};<br>init();</pre><p>And with this done, we can finally make renderCountryLists() a regular function, we also no longer need to call the fetchJSON() function inside it as the init() function already takes care of that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJX8eoa9i2sqjY7p" /></figure><p>And as seen with all the adjustments made, the app still works as it should. Though this part could have been left out, I feel it makes our code a lot nicer and better structured as the only function call we get to make in the global scope is the initializer function itself.</p><h3>Conclusion</h3><p>It’s great you reached the end of the article/tutorial, please pat yourself nicely on the back 😀. The article is aimed at providing a step-by-step walk-through on how to implement pagination, so we can make use of the knowledge in our various future projects whenever the need arises. However, if at any point while reading through the article there was a confusing part, please do well to look at the complete source code, which has been made available <a href="https://codepen.io/Phemy-M/pen/jOdJPBP?editors=1111">here</a> on codepen or you can leave a comment in the comment section of this article and I’ll try to respond to it as soon as I can. Thank you for reading and happy coding.</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcde99b3add" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/pagination-in-javascript-7bcde99b3add">Pagination in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Returning Arrays and Objects from the reduce() Method]]></title>
            <link>https://blog.stackademic.com/returning-arrays-and-objects-from-the-reduce-method-006f899ba4bb?source=rss-a52134ba5b65------2</link>
            <guid isPermaLink="false">https://medium.com/p/006f899ba4bb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Femi Majek]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 14:17:00 GMT</pubDate>
            <atom:updated>2023-12-10T20:22:57.777Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tricks you probably didn’t know about the reduce() method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxySYHmTupZBuXjkb7ht6Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Christopher Gower</a> on <a href="https://unsplash.com/photos/a-macbook-with-lines-of-code-on-its-screen-on-a-busy-desk-m_HRfLhgABo?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>At this point, you’re likely already familiar with most array methods, most especially the map(), filter(), and reduce() methods. However, what you probably didn’t know is that some of the things you’d originally do with the map() and filter() methods can also be done using the reduce() method. We can return arrays and even objects from the reduce() method, as well as use it as a counter depending on the task it’s needed for. Without wasting much time, let’s look at some of these scenarios where the reduce() method could come in handy.</p><h3>Using reduce() instead of filter()</h3><p>Suppose we’re giving an array ages that contains ages of different people and we’re asked to make an array of the ages that fall within the age required to obtain a driver’s license(i.e. ages &gt;= 18). Ordinarily, we’d do this using the filter() method like this;</p><pre>const ages = [14, 19, 16, 23, 12, 38, 20, 17, 10, 18];<br><br>const legalAge = ages.filter((el) =&gt; el &gt;= 18);<br><br>console.log(legalAge); // the result returns [19, 23, 38, 20, 18]</pre><p>The result of legalAge returns the array of ages that meet the age requirement needed to obtain a driver&#39;s license(which are ages greater than or equal to 18). We can however do the same thing above using the reduce() method and still get the same result.</p><pre>const ages = [14, 19, 16, 23, 12, 38, 20, 17, 10, 18];<br><br>const ageLegal = ages.reduce((acc, el) =&gt; {<br>if (el &gt;= 18) acc.push(el);<br>return acc;<br>}, []);<br><br>console.log(ageLegal); // result returns [19, 23, 38, 20, 18]</pre><p>To achieve this, we’ll need a function body and also need to initialize our accumulator(acc) as an array. In our reduce() method we then set a condition that pushes the current element in the iteration into our accumulator array(acc) only if it’s greater or equal to “18” and also explicitly return our accumulator(because in a function body, the accumulator doesn’t get returned automatically).</p><h3>Using reduce() instead of map()</h3><p>Supposing we’re given an array of values then asked to divide the values of this array by two and store the result in a new array, we could do this with the map() method like this;</p><pre>const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];<br><br>const arrHalf = arr.map((el) =&gt; el / 2);<br><br>console.log(arrHalf);<br>// result returns [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]</pre><p>Alternatively, we could also use the reduce() method for the task like this;</p><pre>const halfRed = arr.reduce((acc, el) =&gt; {<br>acc.push(el / 2);<br>return acc;<br>}, []);<br><br>console.log(halfRed);<br>// result returns [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]</pre><p>We initialize our accumulator as an empty array and then push the current element divided by two into the array in each iteration, the accumulator is also explicitly returned.</p><h3>Returning an object from the reduce() method</h3><p>Supposing we’re given an array containing a set of transactions (withdrawals and deposits), and we’re told to make an object that contains the properties deposits and withdrawals based on the given array. Here’s how we’d go about it using the reduce() method;</p><pre>const transactions = [-100, 200, 350, -400, -10, 30, -8, 120, 20];<br><br>const transactionObj = transactions.reduce(<br>(acc, el) =&gt; {<br>el &lt; 0 ? (acc.withdrawals += el) : (acc.deposits += el);<br>return acc;<br>},<br>{ deposits: 0, withdrawals: 0 }<br>);<br><br>console.log(transactionObj);<br>// result returns {deposits: 720, withdrawals: -518}</pre><p>Our accumulator is initialized as an object containing the properties deposits and withdrawals with both having initial values of zero. Then in each iteration, using the ternary operator we add the current array value to the deposits or withdrawals properties depending on whether it’s (i.e. the current value) greater than zero or not. Finally, we also explicitly return our accumulator object.</p><h3><strong>Counting with the reduce() method</strong></h3><p>Assuming we’re told to count the number of deposits in the transactions array from above(i.e. Transactions greater than zero), without much thought we could use the filter() method to filter for the values greater than zero and simply take the length of the returned array as we have below;</p><pre>const transactions = [-100, 200, 350, -400, -10, 30, -8, 120, 20];<br><br>const numDeposits = transactions.filter((el) =&gt; el &gt; 0).length;<br><br>console.log(numDeposits); // result returns 5</pre><p>As seen above the numDeposits returns the value 5 which is the result of the number of deposits in the transactions array. Alternatively, we could also do it with the reduce() method like this;</p><pre>const transactions = [-100, 200, 350, -400, -10, 30, -8, 120, 20];<br><br>const depositsNum = transactions.reduce((acc, el) =&gt; (el &gt; 0 ? ++acc : acc)<br>, 0);<br>console.log(depositsNum); // result returns 5</pre><p>In the above method, our accumulator is initialized as zero, and then in each iteration using a ternary operator we add one to the accumulator if the current element is greater than zero and return the accumulator from the previous iteration if the current element is less than zero. Note that we used ++acc instead of acc++, this is because directly returning acc++ doesn’t give the desired result as zero is returned in each iteration.</p><h3><strong>Conclusion</strong></h3><p>This article is in no way aimed at convincing readers to abandon the traditional methods they use in carrying out operations on arrays that they’re already used to. Instead, it’s just to show readers some other nice ways of carrying out array operations in JavaScript using the reduce() method and also show a few enhanced(unconventional) functionalities that can be implemented with the reduce() method. Thank you for reading and happy coding.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=006f899ba4bb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/returning-arrays-and-objects-from-the-reduce-method-006f899ba4bb">Returning Arrays and Objects from the reduce() Method</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three ways of Implementing Prototypal Inheritance in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/three-ways-of-implementing-prototypal-inheritance-in-javascript-f61f0a92101a?source=rss-a52134ba5b65------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61f0a92101a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Femi Majek]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 06:27:11 GMT</pubDate>
            <atom:updated>2023-10-25T08:41:13.268Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Three Ways of Implementing Prototypal Inheritance in JavaScript</strong></h3><h4><strong>A complete beginner’s guide</strong></h4><p>In this article we’ll be discussing how we can programmatically create objects and how objects are linked to their prototypes, in essence, we’ll be talking about how we can implement Object Oriented Programming (OOP) in JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O5oXBUVl97FOkora" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode">altumcode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Prerequisites</h3><ul><li>Good knowledge of the “this” keyword</li><li>Knowledge of regular object literals</li><li>Familiarity with creating and calling object methods in regular object literals</li></ul><h3>Introduction</h3><p>OOP is a programming paradigm that was developed with the goal of organizing code to make it more flexible and easier to maintain. Before OOP we might just have a bunch of codes gathered across multiple functions or even global scope without any particular structure, which makes it very hard to maintain large code bases let alone add new functionalities to them. So OOP was basically created as a solution to this problem.</p><h3>Implementing OOP in JavaScript</h3><p>There are three ways in which we can implement OOP in JavaScript, they are</p><ul><li>The constructor function technique</li><li>ES6 classes</li><li>Object.create() function</li></ul><h3>The constructor function Technique</h3><p>Constructor functions are a way of creating objects programmatically using a function, this function will be used to set the newly created object’s prototype. It is how built-in objects like arrays, maps, and sets are implemented, it’s also how OOP has been done in JavaScript since the beginning.</p><h3>How do we create objects with constructor functions?</h3><p>To create a constructor function, there’s a convention for their names to start with an uppercase letter. The properties of the object(s) we want to create are set using the “this” keyword alongside the property names, all done inside the constructor function. This constructor function will serve somewhat like a blueprint, a blueprint from which multiple objects can then be created.</p><p><strong>Example:</strong> to create a constructor function which we’ll call Person, from which we’ll create actual objects that have properties that describe different individuals.</p><pre>&quot;use strict&quot;;<br>const Person = function (firstName, height, age) {<br>  this.firstName = firstName;<br>  this.height = height;<br>  this.age = age;<br>};<br>// Here the constructor function is &quot;Person&quot;<br>// Properties firstName, height, and age are set using the &quot;this&quot; keyword</pre><p>We have now created our first constructor function called Person, and as shown above, it is a completely normal function, the major difference between a regular function and a constructor function is that we call the constructor function using the new operator. Also, the properties defined in Person will be the actual properties of every object created using the Person constructor.</p><h3>Creating a new object and calling a constructor function</h3><p>As said earlier we call constructor functions using the newoperator. Let’s now create a new object for an individual rebecca, the rebecca object will contain the properties firstname, height, and age just as we specified in our Personconstructor. We’ll be doing this by calling the Person constructor using the new operator and storing our result in a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXsjFaylmHvmUq43" /></figure><p>As seen above we have now created the new object rebecca and inside the rebecca object(as shown on the right side) we have the firstName, height, and age properties. And so now with this supposed blueprint(Person), we can create multiple individual objects using the same template. Objects created from a particular constructor function are also said to be “instances” of that constructor function, in other words, we can now say that rebecca is an instance of Person. Let’s now create two new objects joy and dave</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWJWF__kzbuRouft" /></figure><p>Two new objects joy and dave have now also been created using the same constructor function which is the Person constructor function. And just like regular objects we can access the properties of these different objects using the “dot” notation e.g to access the firstName property in object dave we can simply do this “console.log(dave.firstName)” and our result returns the string “Dave”.</p><h3>Adding Methods to objects using constructor functions</h3><p>Adding methods to objects as regards constructor functions is quite simple, we can create methods directly inside our constructor functions and every object created using the constructor function will have the method inside of them.</p><p><strong>Example:</strong> To create a method called describe that logs a brief description of an individual to the console based on the individual’s object properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW46qA2q-lfaxkPGJgnMlw.png" /></figure><p>In this case, we’re making use of the rebecca object, and just like any of its other properties, rebecca can make use of the describe method. Calling the describe method on rebecca we get the specified string logged to the console(as shown on the right side), a look at the rebecca object in the console also shows that the describe method is present in it. However, even though this works it is a very bad approach and is not good for code performance. It might not seem like much of a problem if we were to create just two to ten objects, but what if we need hundreds or even thousands of different objects? This means we’d essentially be creating the same function separately for each of these objects and this violates the “keeping our code dry” principle. Instead, there’s a better way of adding methods to our objects using something called “Prototypes’’.</p><h3>Prototypes</h3><p>Every function in JavaScript(constructor functions included) automatically has a special property called “prototype”, now every object that’s created using a certain constructor function will get access to all the methods and properties that we define in this “prototype” property of said constructor function. Please note that this “prototype” property is NOT the prototype of the constructor function(it is only a property inside the constructor function). Instead, it’ll be the prototype of all objects that’ll be created using said constructor function(and this prototype can be accessed in the newly created object(s) via their __proto__ property). Using our Person constructor as a reference point, we can now say that all instances of the Person constructor function will have access to all the properties and methods defined in Person.prototype (Person.prototype being the prototype property of Person). So once again every object created from the Person constructor will inherit the methods and properties that are defined in the prototype property of Person. Now that this has been well established we can proceed to define methods in this prototype property.</p><p><strong>Example: </strong>To create a method called calcBirthYear on Person.prototype, which calculates and logs to the console the birth year of the individual on which the method is called.</p><pre>const Person = function (firstName, height, age) {<br>  this.firstName = firstName;<br>  this.height = height;<br>  this.age = age;<br>};<br><br>Person.prototype.calcBirthYear = function () {<br>console.log(2023 - this.age);<br>};</pre><p>We have now successfully created the calcBirthYear method on Person.prototype. With this done, we can now use the calcBirthYear method on rebecca as if it were declared inside of rebecca itself. Since rebecca object was created from the Person constructor function, and we said earlier that any object created using the Person constructor will inherit all the properties and methods defined in Person.prototype, therefore we can now call the calcBirthYear method on rebecca like this &quot;rebecca.calcBirthYear&quot;, and it’ll work as if the method had been declared inside of rebecca itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ijZTGn6-GbHy4vLF" /></figure><p>And now on calling the calcBirthYear method on rebecca, we get the result `1998` as shown on the right which is the actual birth year of rebecca.</p><p>We can also confirm if the earlier statement about Person.prototype being the prototype of all objects created from the Person constructor is true, we’ll test using the rebecca object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o_7_p6Kdet5SrBr5" /></figure><p>As seen above a strict comparison between Person.prototype and rebecca.__proto__ returns true, calling the in-built method isPrototypeOf on Person.prototype with rebecca object being the argument also returns true(the method checks if Person.prototype is the prototype of rebecca). Lastly, the result of logging rebecca.__proto__ and Person.prototype to the console returns the same object, which both contain the calcBirthYear method. This indeed proves that Person.prototypeis the prototype of rebecca and this will also be true for all other instances of the Person constructor function.</p><p>We can also call the calcBirthYear method on every object we create using the Person constructor including the ones we’ve already created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GvVD_bhH2lLQZHCo" /></figure><p>And just like we did with rebecca we’re also able to call the calcBirthYear method on both joy and dave, in both cases, their respective birth years get logged into the console. We’ll stop here for now with constructor functions, so let’s move on to ES6 classes.</p><h3>ES6 Classes</h3><p>Introduced in ECMAScript 2015, ES6 classes allow us to do the same thing we did so far with constructor functions, but this time with a much nicer and more modern syntax. Do note that JavaScript classes do not work like traditional classes in other languages like Java or C++, instead, JavaScript classes are like syntactic sugar over what we learned previously on constructor functions. Let’s implement what we did with Person this time using ES6 classes.</p><p>Similar to functions we have class declarations and class expressions(we’ll be sticking to class declarations in this article)</p><pre>// Class expression<br>const PersonClExpression = class {<br>  constructor(firstName, height, age) {<br>  this.firstName = firstName;<br>  this.height = height;<br>  this.age = age;<br>  }<br>};<br><br>// Class declaration<br>class PersonCl {<br>  constructor(firstName, height, age) {<br>  this.firstName = firstName;<br>  this.height = height;<br>  this.age = age;<br>  }<br>};</pre><p>When building a class, the first thing we do is add a “constructor” method, the constructor method works in a similar way as a constructor function but in this case, it is a class method and needs to be called “constructor”. Just like in constructor functions, we pass in parameters/arguments which will be the properties we want our object(s) to have. As seen above we’ll be having the same properties in PersonCl just as we previously had when we used constructor functions.</p><h3>Creating a new object with ES6 classes</h3><p>Creating new objects with classes also works in the same way as before when we used constructor functions, we create objects using the new operator. In classes whenever we create a new object with the new operator the constructor method automatically gets called, and we usually refer to the newly created object(s) as “instances” of said class. Now let’s create two new objects which we’ll call tony and andre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jooPxxMbhSGqAPrG" /></figure><p>We have now created objects tony and andre by calling our PersonCl class with the new operator, both objects having the firstName, height, and age properties as shown on the right. We can therefore say that tony and andre are both instances of PersonCl, meaning both are objects created from the PersonCl class. And just like every other object, we can access properties on both using the “dot” notation.</p><h3>Adding Methods to classes</h3><p>Adding methods to classes is pretty straightforward, all we have to do is create the method(s) inside of the class(inside the class and not inside the class’ constructor method). It is important to note that every method created inside a class will be in the prototype(__proto__ property) of the object(s) created from this class and not directly on the newly created objects themselves. This is similar to what we saw in the case of constructor functions, in which objects inherited methods from the prototype property of their constructor. All this works BTS because of “The prototype chain and prototypal Inheritance” We’ll dive deeper into them some other time. For now, we’ll continue learning how to implement prototypal inheritance.</p><p><strong>Example: </strong>To create a method calcBirthYear on the PersonCl class, which calculates and logs to the console the birth year of the individual on which the method is called.</p><pre>class PersonCl {<br>  constructor(firstName, height, age) {<br>  this.firstName = firstName;<br>  this.height = height;<br>  this.age = age;<br>}<br><br>calcBirthYear() {<br>  console.log(2023 - this.age);<br>  }<br>}</pre><p>We have now successfully declared our calcBirthYear method in the PersonCl class and as seen above the calcBirthYear method is written inside the PersonCl class(not inside the constructor) Also the method is written without the “function” keyword. And now just like with constructor functions we can call the calcBirthYearmethod on every object created from the PersonCl class as if it were originally declared in the object itself. Let’s confirm this by calling the calcBirthYear method on our tony and andre objects that were previously created using the PersonCl class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ErjLnePASnA6BjI7" /></figure><p>On calling the calcBirthYear method on both tony and andre the method works just fine as if it had been declared inside both objects and in both cases, we get their respective birth years logged to the console as shown on the right(2001 and 2005 respectively).</p><p>As we can see PersonCl acts just like any other constructor function, but this time it appears to have a much nicer syntax. With this syntax we don’t necessarily have to mess with the prototype property, all we have to do is write the method(s) inside of the class(outside the constructor) and they’ll be automatically added to the prototype property of the class. However, it is worth knowing that methods and properties can also be set manually on the prototype property and they’ll work just fine.</p><p>To show this we’ll be using our old friend the describe method, which logs to the console a simple description string of the individual on which it is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4uBipSE9hRVM5wOb" /></figure><p>Now we have manually added a method (describe) to the prototype property(PersonCl.prototype) of the PersonCl class, similar to what we did earlier with the Person constructor function. And just like the other method(calcBirthYear) we previously created, we were able to call describe on the tony object as if it were written inside the tony object itself. Lastly, please note that to declare/create multiple methods inside a class there’s no need for commas i.e. consecutive methods are simply declared on a new line without any commas.</p><h3>Object.create() function</h3><p>We’ve learned about constructor functions and ES6 classes, but there’s also a third way of implementing prototypal inheritance which is using a function called “Object.create()”, this Object.create() function works differently from, constructor functions and classes. With Object.create(), there’s still the idea of prototypal inheritance however, there are no prototype properties involved, no constructor functions, and new operator. Instead, we can use Object.create() to manually set the prototype of an object to any other object that we want. After creating the prototype, we can then insert the methods we want to be inherited inside it. Since we now know we can set the prototype of an object to any object that we want, let’s create an object that’ll serve as the prototype of all the objects of different individuals that we create.</p><p><strong>Example: </strong>To create an object called PersonProto which will be the prototype of all the objects we create for different individuals.</p><pre>const PersonProto = {<br>  calcBirthYear() {<br>  console.log(2023 - this.age);<br>  },<br>};</pre><p>We have successfully created our PersonProto object and it’ll serve as the prototype of all objects created for different individuals. Now to set PersonProto as the prototype of these objects all we have to do is call the Object.create() function and pass in the PersonProto object, then it’ll automatically be the prototype of the newly created objects. Let’s now set PersonProto as the prototype of a new individual object peter.</p><pre>const PersonProto = {<br>  calcBirthYear() {<br>  console.log(2023 - this.age);<br>  },<br>};<br>const peter = Object.create(PersonProto);</pre><p>On calling the Object.create() function and passing in the PersonProto object as argument(as shown above), a new empty object is returned(the returned object is what gets stored into the peter variable) with its prototype set to PersonProto. In other words, peter is now an empty object that is linked to the PersonProto object which is its prototype(PersonProto is now the prototype of object peter). And this can be confirmed by simply taking a look at the __proto__ property of peter(recall that the prototype of any object can be accessed by its __proto__ property)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wjMeUW5j5v5MdSqd" /></figure><p>As shown above the result of peter.__proto__ returns as the PersonProto object and a strict comparison between the two also returns true(i.e. PersonProto === peter.__proto__ returns true). This proves that the prototype of peter is indeed PersonProto.</p><p>At this point we might wonder “How then do we set the properties of the newly created object programmatically?”, It’s pretty straightforward, all we have to do is insert another method into the PersonProto object which will be responsible for setting the object’s (peter in this case) properties and then call the method on the newly created object. Let’s now create a method setProperties inside PersonProto which will be used to set the properties of the peter object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ZLmflGkVrg_H-lf" /></figure><p>As seen, we can set the firstName, height, and age properties on peter by calling the setProperties method on it. And just like every other object we’ve created so far we can call the calcbirthYear method on peter and it’ll work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iy4W91ix9wHg7t3M" /></figure><p>On calling the calcbirthYear on peter we get the correct birth year logged into the console.</p><h3>Conclusion</h3><p>When we use the “new” operator in constructor functions or classes, it automatically sets the prototype of all the instances(by instance we mean all objects created from a particular constructor or class) to the constructor’s prototype property, all of this happens automatically behind the scenes. On the other hand with Object.create() we can set the prototype of objects manually to any object that we want. In our case, we manually set the prototype of the peter object to the PersonProto object, and with that, the two objects were effectively linked through the __proto__ property just like in the two previous cases.</p><p>The reason Object.create() is the last discussed way of implementing OOP in JavaScript is because in practice (real-world scenarios) it’s kind of the least used way of implementing prototypal inheritance. However, it’s still very important to know exactly how it works because we’ll eventually still come across them in the real world. More importantly, it will become really useful in linking prototypes when we implement inheritance between classes.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61f0a92101a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/three-ways-of-implementing-prototypal-inheritance-in-javascript-f61f0a92101a">Three ways of Implementing Prototypal Inheritance in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>