<?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 Allan Sendagi on Medium]]></title>
        <description><![CDATA[Stories by Allan Sendagi on Medium]]></description>
        <link>https://medium.com/@allansendagi?source=rss-36e7c437b31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4wufl5U1bUxq2BVEZ0PLlA.png</url>
            <title>Stories by Allan Sendagi on Medium</title>
            <link>https://medium.com/@allansendagi?source=rss-36e7c437b31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:04:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@allansendagi/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[Introducing NOMOS]]></title>
            <link>https://medium.com/@allansendagi/introducing-nomos-f03ef902e803?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/f03ef902e803</guid>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Tue, 26 May 2026 07:27:44 GMT</pubDate>
            <atom:updated>2026-05-26T07:27:44.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAaKQTV23Ss-Swi7SEa9Jw.png" /></figure><p>Foundational Paper I &amp; II Operational Logic Infrastructure for the Autonomous Era; Why Intelligence Alone Cannot Scale — and the Missing Layer Every Organization Now Requires <a href="https://t.co/KNbfIUmvwh">https://nomosprotocol.com/whitepaper</a></p><p>The Emergence of Operational Logic: A Theory of Organizational Decision Systems; A Foundational Framework for Understanding Organizations as Behavioral Decision Systems <a href="https://t.co/KNbfIUmvwh">https://nomosprotocol.com/whitepaper</a></p><p>Developer Documentation: <a href="https://t.co/jgeHRGtEPQ">https://nomosprotocol.com/docs</a> Product Hunt: <a href="https://t.co/7kAy25yzEk">https://producthunt.com/products/nomos?utm_source=other&amp;utm_medium=social</a> Landing Page: <a href="https://t.co/QNNpXCbZsq">http://nomosprotocol.com</a> For questions or inquiries: allan@nomosprotocol.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f03ef902e803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cheap Changes Everything: Borrowing “Price” from Economists to understand the true impact of AI on…]]></title>
            <link>https://medium.com/@allansendagi/cheap-changes-everything-borrowing-price-from-economists-to-understand-the-true-impact-of-ai-on-4a71da903227?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a71da903227</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[perspective-on-ai]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 20:39:40 GMT</pubDate>
            <atom:updated>2024-03-31T20:39:40.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cheap Changes Everything: Borrowing “Price” from Economists to understand the true impact of AI on our Civilisation.</h3><p>New technologies like Generative AI are often labeled as ‘Transformational’ — language perhaps useful for technologists and industry people, but not much else.</p><p>For the rest of us, what we need is a relatable model we can put on, like a set of goggles, allowing us to see how all this will impact our lives and cascade through the broader economy.</p><p>“When the price of something falls, we use more of it. That’s simple economics and is happening right now with AI.”<br>This is one such model Economist Joshua Gans and his colleagues give us in “Predictive Machines” to help us cut through the noise.</p><p>It’s a conversation we must have because, for many of us, the current wave of AI doesn’t bring “True Intelligence”; consequently, we have overlooked its disruptive potential.</p><p>But with price goggles on, AI is making something else exponentially cheaper and more ubiquitous: Prediction.</p><p>The authors define prediction as the process of filling in missing information by taking the information you have, often referred to as ‘Data,’ and using it to generate information you don’t have.</p><p>Prediction is a central input into decision-making, and its radical democratization unlocks unforeseen opportunities across industries.</p><p>Consider light. In the early 1800s, it cost four hundred times more than today. This made people think twice before using artificial light. The subsequent price drop lit up the world, enabling us to live and work in buildings where natural light couldn’t penetrate.</p><p>Similarly, when the cost of arithmetic dropped, unforeseen applications emerged, such as photography.</p><p>With the internet, although goods and services could be distributed digitally and communication became easy, these capabilities existed before. From a purely economist’s perspective, what changed was that they were now cheap!</p><p>Prediction, like light, the internet, and arithmetic, is now used for traditional tasks like inventory management and demand forecasting, but its decreasing cost has expanded its application to non-traditional prediction problems.</p><p>For example, transportation is now a prediction problem. Autonomous cars, which once operated only in controlled environments, now rely on prediction.</p><p>They continuously analyze data from sensors and algorithms to anticipate the behavior of other vehicles, pedestrians, and road conditions, enabling them to navigate safely in real time.</p><p>At lower levels, a Prediction machine can save costs by handling predictive tasks. But as the machine cranks up, a highly accurate and reliable prediction machine may fundamentally change how an organization operates and its business model.</p><p>Perhaps computers still cannot think, but prediction is everywhere in our lives, hidden away as decisions we have to make on a day-to-day basis, both in our personal lives and in business. It’s a thread that guides how we live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a71da903227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[- — To People Who Want To Shape The Future — But Can’t Get Started-]]></title>
            <link>https://medium.com/@allansendagi/to-people-who-want-to-shape-the-future-but-cant-get-started-874c89baa8b7?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/874c89baa8b7</guid>
            <category><![CDATA[innovation]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 06:39:18 GMT</pubDate>
            <atom:updated>2022-08-02T06:39:18.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>- — To People Who Want To Shape The Future — But Can’t Get Started-</h3><p>Busying yourself with daily life, while noble, means you’ve outsourced responsibility for deciding the kind of world you and your children should live in.</p><p>Imagine I’m filming a mini-documentary of you as you go about your daily life. It will capture essential elements such as going to work, caring for children, and looking after elderly parents.</p><p>The film makes it obvious that you have more pressing things to do than, say, help shape the direction of the world. Such ideas it would seem are a luxury you cannot afford.</p><p>Since you can’t guarantee that the contractor making decisions on your behalf has your best interests at heart, they’ll likely give you a future you don’t want.</p><p>And you’ll just have to live with the consequences of your decision to sit on the sidelines.</p><p>So today I want to talk about:<br>1. Innovation as a way to shape the direction of the world<br>2. Adopting innovation to cause fundamental change on a national level<br>3. The future we are building at RARL</p><p>— — 1. Innovation as a way to shape the direction of the world — -</p><p>War, activism, or innovation?<br>Penicillin — nearly a century old helped extend life. The internet &amp; photography have helped to expand the human intellect, and the automobile &amp; airplane enabled the physical movement of goods and people.</p><p>Innovation is the process by which we solve human problems. Every time we solve a difficult problem, we inch our civilization forward.</p><p>These 3 innovations left the world better off than any war, or activism efforts.</p><p>— -2. Adopting innovation to cause fundamental change on a national level— -</p><p>Should Koreans build for Koreans? Ugandans solve for Ugandans?<br>In the 1970s, Korea was one of the poorest countries in the world.</p><p>Koreans had to learn to solve their own problems with simple, cheap affordable products for locals.</p><p>Koreans for Koreans created growth and the capability to produce good products that could later be sold around the world.</p><p>People must be empowered to solve their own problems. This is the only sustainable, effective and dignified way to prosperity. For fundamental change to happen, people need to own the solution.</p><p>— -3. The future we are building at Running All Red Lights — -</p><p>Why is calculus so hard?<br>Poor communication makes calculus ugly.</p><p>Brains don’t think in terms of English or mathematical symbols. Conveying sophisticated ideas to each other using ugly &amp; unrelated words, symbols, and sounds is self-defeating.</p><p>Innovation is difficult because we don’t have a simple language for it; we don’t know what causes it to succeed.</p><p>The way we get more people to solve problems is through sound theory-building.</p><p>Theory is how we replicate success and tame complexity. Theory gives us a common language — a lens anyone can put on to understand a problem.</p><p>At Running All Red Lights, we want to elevate innovation from a game of luck to predictable so that more of humanity can help us solve important problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=874c89baa8b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jobs to be done — A sound theory for innovation.]]></title>
            <link>https://medium.com/@allansendagi/jobs-to-be-done-a-sound-theory-for-innovation-cb1bbd613148?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb1bbd613148</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[jobs-to-be-done]]></category>
            <category><![CDATA[innovation-management]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 02:21:06 GMT</pubDate>
            <atom:updated>2022-08-02T15:52:24.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jobs to be done — A sound theory for innovation?</h3><p>A quick google search reveals a 90% startup failure rate. These high failure rates have become commonplace, if not expected because we’ve come to view innovation as a game of luck.</p><p>But how can we live with that?</p><p>Suppose patients died 90% of the time. We wouldn’t say “Doctors, you are not failing hard enough. Here is $1M to fail even harder until you figure it out”. We would spare no effort to get to the root of the problem.</p><p>Doctors failed hard until a better theory — the germ theory was developed to explain what caused people to get sick. Up until that point, treating disease was a game of luck — a fact of life.</p><p>A lack of a proper theory for innovation and entrepreneurship may not directly kill people, but it certainly kills dreams, spirits, and careers, as well as wasting vast sums of money. There seems to be no end in sight.</p><p>For the past two years, I’ve looked for a sound theory that could make innovation predictable, profitable, and sustainable. The answer to this puzzle is “jobs to be done”.</p><p>A good theory explains how and why, and it doesn’t change its mind.</p><p>The theory had to meet 4 conditions for me to consider it:<br>- Causality. It had to explain what causes people to buy products or services.<br>- Simplicity. A 5-year-old must get it. Simple is natural.<br>- Descriptive, not prescriptive. It shouldn’t tell us what to build or how to build. It appreciates the complexity of innovation. <br>- Language. It had to give us the right language to talk about innovation.</p><p>I studied MIT Bill Aulet’s 24 steps, Doblin’s 10 types, Alex Osterwalder’s Business Model Generation, Six Sigma principles, Design thinking in engineering, Agile Framework in computer science, Eric Ries lean start-up, active learning in physics, Adaptive army in the military and the Disruption theory.</p><p>All the above do not explain causality — most aren’t theories. They provide no explanation for why or how any natural or social phenomenon occurs.</p><p>Design thinking, eg, helps people understand a customer problem. It emphasizes deep empathy with the customer, rapid iteration, and divergent thinking. It recognizes the value of experiences over product attributes.</p><p>It doesn’t, however, provide me with a causal explanation for why customers will embrace some innovations but not others, nor does it provide me with the language for deeply understanding the insights about customers that are truly important, nor does it address the need to find the right business model.</p><p>Lean start-up excels at prototyping the solution to a problem but often provides little guidance on generating ideas or determining whether you’ve found a problem worth solving.</p><p>Jobs theory gives me the language and thought process. “What job did you hire that product to do?” It provides a strong set of tools for developing the deep customer insights required by design thinking, as well as inspiring solutions that customers will want to buy and use.</p><p>Jobs theory tells us that humans are forever seeking progress. This quest for progress is the bedrock of all great innovations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1bbd613148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Look at Functional Programming (FP)]]></title>
            <link>https://medium.com/swlh/a-comprehensive-look-at-functional-programming-fp-4a87629ecaed?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a87629ecaed</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 03:42:34 GMT</pubDate>
            <atom:updated>2020-08-09T07:56:12.364Z</atom:updated>
            <content:encoded><![CDATA[<h4>A programming paradigm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctHOAIb12wOKKLTuCH0nPQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@magda-ehlers-pexels?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Magda Ehlers</a> from <a href="https://www.pexels.com/photo/pile-of-white-and-black-boxes-1329318/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>This is the other major programming paradigm. If you are interested in Objected oriented programming, I have written about it here…</p><p><a href="https://medium.com/dev-genius/a-comprehensive-look-at-object-oriented-programming-oop-91d6423dde9a">A comprehensive look at Object-Oriented Programming(OOP)</a></p><p>*This article is inspired by <a href="https://www.udemy.com/user/andrei-neagoie/"><strong>Andrei Neagoie</strong></a>’s Advanced concepts in Javascript course. I highly recommend it<strong>*</strong></p><p>Here is what to expect from this article:</p><ol><li><strong>Currying</strong></li><li><strong>Partial application</strong></li><li><strong>Pure functions</strong></li><li><strong>Referential transparency</strong></li><li><strong>Compose</strong></li><li><strong>Pipe</strong></li></ol><p>We know that <a href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming</a> has existed for over 60 years.<a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)"> Lisp </a>— a popular programming language was first developed in 1958. The idea of functional programming originates from <a href="https://plato.stanford.edu/entries/lambda-calculus/">Lambda calculus</a> — a formal system in mathematical logic.</p><p>Today, the popularity of functional programming has surged because programming languages built on this paradigm such as <strong>Haskell</strong>, <strong>Scala, </strong>and<strong> Closure</strong> work well with distributed computing. <br>In distributed computing, you have multiple machines interacting with data; but also in Parallel computing where machines work on data at the same time.</p><p>Javascript libraries like Redux and React have also popularised the idea of functional programming.</p><h3>So, what is FP anyway and how can we use it as Programmers?</h3><p>Just like OOP, Functional programming is all about separation of concerns. We package our code into separate chunks so that everything is well organized. Each part of our code concerns itself with one thing that it’s good at.</p><p>Classes in OOP divide up properties and methods; FP also separates data and functions. For a functional programmer, the world is data that gets interacted with. Data and functions aren’t one piece or one object.</p><blockquote>For a Functional programmer, the world is data that gets interacted with; data and functions aren’t one piece or one object.</blockquote><p>Although there is no one definition of what is or what isn&#39;t functional, mostly functional programming languages have an emphasis on simplicity where data and functions are concerned.</p><p>Functions just operate on well-defined data structures like arrays and objects rather than belong to them, unlike OOP and objects.</p><p>However, the goals of functional programming are the same as Object-oriented programming:</p><ol><li>Make code more clear and understandable.</li><li>Make code easy to extend so that as our app grows, and as our programs grow, as the developer team grows, our code still remains easier to extend.</li><li>Make code easier to maintain by multiple programmers.</li><li>Make our code memory efficient by having these reusable functions that act on data.</li><li>Keep our code DRY. We avoid repeating ourselves. Our code is clean and efficient.</li></ol><h3>Pure functions</h3><p>Unlike OOP where we have the four pillars(<strong>Encapsulation, Abstraction, Inheritance, Polymorphism</strong>), with FP it all comes down to this concept — <a href="https://en.wikipedia.org/wiki/Pure_function"><strong>Pure functions</strong></a><strong>.</strong></p><p>The idea here is that there is a separation between the data of a program and the behavior of a program.</p><p>And all objects created in FP are immutable — once something is created, it cannot be changed. We avoid things like shared state and adhere to this principle of pure functions. As you will find out, in functional programming, there are a lot of things you can’t do.</p><blockquote>A function always has to return the same output given the same input no matter how many times we call it; it cannot modify anything outside of its self — no side effects.</blockquote><p>A function always has to return the same output given the same input no matter how many times we call it; it cannot modify anything outside of its self — no side effects.</p><h4>1. No side effects</h4><p>Let&#39;s have an array to demonstrate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*eBY5JMErkzC-AaQH6Z973g.png" /><figcaption>ZTM</figcaption></figure><p>This function has <strong>side effects</strong>. Here is how we can tell:</p><p><em>Does the function modify anything outside of its self?</em></p><p>Here it does. It modifies the array that lives outside of its self in the global object. Hence we don&#39;t know what might happen to the array. Anybody can call it and change it.</p><p>If I call <em>a(array)</em> again, my array is again modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*5iPmeWMyohZ3liG1y-wWeQ.png" /></figure><p>Let’s have another function with side effects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*3gEX7uc_QU0JHjLIWkiyvA.png" /><figcaption>We are still modifying the array in our global environment</figcaption></figure><h4>2. Shared state</h4><p>With side effects, you are using a shared state that can interact with anything. Here the order of a function call matters which can also cause a lot of bugs.</p><p><strong>So how can we write something that has no side effects? Something that won’t change whatever our array is?</strong></p><p>Well, we can copy the array inside our function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*PjytHNGPDK7HeeEhLfpa4A.png" /></figure><p>The <em>newArray</em> will be the same exact thing as our global <em>array</em>. Note here that we have used the <strong>concat()</strong> method instead of doing<strong> = </strong>which would have given us the reference to the array— remember objects are passed by reference.</p><p>So instead of having them point in the same direction, this way we have a new copy of the <em>array</em>.</p><p>Now we can just do <em>newArray.pop() </em>and return <em>newArray. </em>And we can see that the original array hasn&#39;t changed.<br>Although we created a new state inside the function, its a local variable. We are not modifying anything outside of our scoped world.</p><p>And because it doesn&#39;t affect the outside world, we know what to expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*pThKKIk2ih5Zubyi0d4MbA.png" /><figcaption>map returns a copy of the array</figcaption></figure><p>None of my arrays have changed. We have three distinct arrays. And all these functions have no side effects. They don&#39;t affect anything that&#39;s outside of their world.</p><p>But here is an interesting case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*s4eB1HEgiNGgXqtF2WpJ4A.png" /></figure><p>This is not a pure function. <em>console.log()</em> uses the browser to log something to the browser. It’s logging something to the outside world hence modifying something outside of itself hence side effects.</p><h4>3. The input should always result in the same output</h4><p>Does the function always return the same output given the same input?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*CFARvpN4DcKJbGoyp7gqOg.png" /></figure><p>Here the result is always the same no matter how many times I run the program. This is also known as <a href="https://en.wikipedia.org/wiki/Referential_transparency">Referential transparency.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*QEA2sJI4PCnnZmnOvp-jkg.png" /><figcaption>Referential transparency</figcaption></figure><p>Referential transparency says: If I change the contents of <em>a</em> to <em>7</em>, can that have any effect on the program? The answer is no because no matter what, if my input is the same, I am always going to get the same output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*6lwBxxljefvDPEEnXvBlKQ.png" /></figure><p>Note that these functions have no side effects. They are not touching any outside part of their world. Parameters here are local variables.</p><h3>Can we have 100% pure functions?</h3><p>No, we can’t. Pure functions in a literal sense can’t do anything. A program can’t exist without side effects.</p><p><em>Input-output</em> is a side effect. <em>console.log</em> is a side effect — that is all communication with the outside world.</p><blockquote>Pure functions in a literal sense can’t do anything. A program can’t exist without side effects.</blockquote><p>We can&#39;t run any code without having the side effect of interacting with the browser; we can’t have a website with just pure functions.</p><p>Browsers have to make<strong> Fetch calls</strong>, <strong>HTTP </strong>calls<strong> </strong>to the outside world. We have to interact with the<strong> dom </strong>and manipulate what&#39;s on the website.</p><p>So we can agree that the goal here is not to make everything pure functions; rather the goal is to minimize side effects.</p><p>The idea is to organize your code with a specific part that has side effects so that when you have a bug, you know right away where to go(database calls, API calls, input-output) because this is normally where side effects are happening. The rest of your code should be just pure functions.</p><blockquote>Purity is more of a confidence level. It cannot be 100%.</blockquote><p>Because at the end of the day, we do have to have some sort of global state to describe our application. That&#39;s unavoidable.</p><p>The core of functional programming is very simple. We want to build programs that are built with small, reusable, and predictable pure functions.</p><h4><strong>Characteristics of a perfect pure function</strong></h4><ol><li>A perfect function should do one task and one task only. We don&#39;t want a massive function. We want a simple function that we can test that does one thing well.</li></ol><p>2. It should have a return statement. Every function should return something. When we give it an input, we expect an output.</p><p>3. No shared state with other functions.</p><p>4. Immutable state. We can modify some of the state within our functions but we always return a new copy of that output. We never modify our global state.</p><p>5. The function should be predictable. If we understand with certainty what our function does, it makes our code predictable. Functional programming at the end of the day is all about making your code predictable.</p><blockquote>Functional programming at the end of the day is all about making your code predictable.</blockquote><h3>Key concepts in functional programming.</h3><h4>Idempotence</h4><p>One idea that makes this clear is an elevator button. Pressing an elevator call button more than once has no bearing on the final result. Regardless of the number of times you press the button, the elevator is sent to that floor. Idempotent systems, like the elevator, result in the same outcome no matter how many times identical commands are issued.</p><p>Compare this to a function that returns a random number each time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*t-d5Rp6IPHBdEv6Qy8WnRg.png" /></figure><p>This function always returns a random number between 0 and 1 on every call. It&#39;s not predictable.</p><p>What idempotence means is given the same inputs, a function always does what we expect it to do.</p><p>It’s a lot like pure functions but a little different. If we take the same function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*uW67Q-xSP5w_lDR7iaaKKw.png" /></figure><p>Here no matter how many times I call random, I get 5. The function that <em>console.log’s 5</em> to the outside world, is idempotent. With multiple calls, it&#39;s going to display the same text even though it&#39;s not pure.</p><p>Another thing that can be idempotent is deleting a user from a database. When we delete a user from a database, we delete that person once but if I keep calling the function, to delete the same user, it&#39;s going to return the same result —an empty field where there are no more users.</p><p>Idempotence is used a lot in<strong> API HTTP</strong> requests. You always expect the same result regardless of the number of times a call is made.</p><p>Idempotence is valuable in parallel and distributed computation because it makes our code predictable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*lqXLuEPTfRvEuhiW1mOEqA.png" /></figure><p>Another idea is the ability to call yourself over and over inside of yourself and you still get the same result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*0QXWl6hdVyqCcjLEVSOZwA.png" /></figure><p>Math.abs gives me a positive number or absolute number every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_XG4VUvKDDt0PcH1oQ7UsQ.png" /></figure><p>But no matter what, calling this function over and over inside of itself always returns with the same thing. And so this is a guarantee of code being predictable.</p><h4>Imperative vs declarative</h4><p>Imperative code is code that tells the machine what to do and how to do it.</p><p>Declarative code tells it what to do and what should happen. It doesn&#39;t tell the computer how to do things.</p><p>Think about an image tag. It’s declarative. You include it in your code and you expect an image although you don&#39;t tell the machine how to display it.</p><p>A computer is better at being imperative. It needs to know how to do things. Human beings on the other hand are declarative.</p><p>When we looked at the <a href="https://medium.com/@allansendagi/inside-the-javascript-engine-compiler-and-interpreter-c8faa638b0d9">Javascript engine</a>, we saw how machine code is imperative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*fIUDoDgscrb2wLdm.png" /><figcaption>Imperative vs declarative</figcaption></figure><p>Our machine code tells the computer, for example, to put the variable in that memory space and then take it out here and then modify it there. It’s very descriptive of how to do things vs as we go higher and higher up the chain to a higher-level language, we see declarative behavior.</p><p>We don&#39;t have to say hey, this is where you should store the memory. We just declare a variable with some sort of data and we say what needs to get done but not how to do it. The computer takes care of that for us.</p><p>Another example is for loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*s2Td2lby828j0MQmCAnG-A.png" /><figcaption>Example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*XZ4_fIU9Mn4UxuQi0-19gw.png" /><figcaption>Example 2</figcaption></figure><p>Which one would you say is declarative vs imperative?</p><p><em>Example 1</em> is imperative. We say declare a variable zero. And then loop for 1000 times. Also, increment<em> i </em>by one every time and finally <em>console.log(i).</em><br>There is a lot of instructions here.</p><p>How can we make this more declarative?<em> Example 2</em> is declarative.<br>Here we don&#39;t tell the program what to do or how to do it. I don&#39;t tell it to increment<em> i </em>by 1, or loop through things.</p><p>Another example of this is <em>jquery</em>. <em>Jquery</em> is more imperative than what we have now like <em>React</em>, <em>Angular</em>, or <em>Vue</em>.</p><p>Functional programming helps us be more declarative. We compose functions and we tell our programs what to do instead of how to do it.</p><p>But it’s important to note that at the end of the day, our declarative code is either going to end up either compiling down or being processed by something imperative like machine code. We can’t just avoid side effects and data manipulations.</p><blockquote>But it’s important to note that at the end of the day, our declarative code is either going to end up either compiling down or processed by something imperative like machine code. We can’t just avoid side effects and data manipulations.</blockquote><p>At the end of the day, something has to manipulate the <em>dom</em> on the webpage or talk to a database.</p><p>In the case of something like<em> React</em>, it abstracts away a lot of complexity so that we as programmers don&#39;t have to do it.</p><p>But the React library or Lisp itself eventually has to compile and do imperative things. The idea here is for us to get a level higher into declarative code so that we can be more productive.</p><h3>Immutability</h3><p>This means not changing the state. In OOP we saw classes that you could change. In functional programming, it’s all about immutability.</p><p>You are not changing the state but instead, you are making copies of the state and returning a new state every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*j2Al3pL7RMoUpPtJap2K1g.png" /><figcaption>State Mutation</figcaption></figure><p>We are cloning the <em>obj </em>and so our <em>clone</em> is a pure function. Because no matter how many times I call this function, it&#39;s going to clone — it&#39;s a pure function.</p><p>But you can see that afterward I do <em>obj.name </em>and update the name to <em>Allan. </em>As soon as I do that, the <em>name</em> gets changed to <em>Allan. </em>Here we are mutating the state. We are mutating data in our program.</p><p>In functional programming, the idea of immutability is very important. We can change things inside of our function but we don&#39;t want to affect the outside world in our programs.</p><p>Ideally, if we want to change the name, we would create a function to do just that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*izeftNWEHHwQw1arQeaTeA.png" /><figcaption>source ZTM</figcaption></figure><h4>Structural sharing</h4><p>Here our initial<em> obj James </em>is still there. We have maintained immutability. We are returning copies every time a change is made.</p><p>Now you might say that this is not very efficient. Because we are just copying things over every time we want to make a change and we run a risk of filling up our memory.</p><p>There is something called <a href="https://en.wikipedia.org/wiki/Persistent_data_structure">structural sharing</a>. Functional programming and a lot of places implement this data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*edTe5WDYoNp2NgcqivraqA.png" /><figcaption>Wikipedia</figcaption></figure><p>The idea behind it is that when a new object or any sort of data structure is created, we don&#39;t actually copy everything. If it&#39;s a massive object or array, that is very expensive.</p><p>Instead of sharing the whole copy, underneath the hood, what happens is that only the changes that were made to the state would be copied.</p><p>But the things that don&#39;t change, in memory, are actually still there. And this is called structural sharing. With this in mind and the fact that today&#39;s memory is fairly cheap, it doesn&#39;t make functional programming especially the idea of immutability expensive or wasteful.</p><blockquote>We are just saying that hey this data is not mine. So I am just going to copy it and leave the original intact so that other people can use it as well; just like a kid in school who plays with toys but doesn&#39;t destroy them so that other kids can play with them too.</blockquote><p>We are just saying that hey this data is not mine. So I am just going to copy it and leave the original intact so that other people can use it as well; just like a kid in school who plays with toys but doesn’t destroy them so that other kids can play with them too.</p><h3>HOF and closures</h3><p><a href="https://medium.com/swlh/advanced-concepts-in-javascript-higher-order-functions-hof-ecd673a2a3f7">Advanced Concepts in Javascript — Higher Order Functions(HOF)</a></p><p>HOF is a function that does one or two things:<br>1. Takes one or two functions as arguments</p><p>2. Returns another function as a result often called a callback.</p><p>For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*u5qltsXkApMj5LMnod2FTg.png" /><figcaption>A function that returns a function is a HOF</figcaption></figure><p>or</p><p>It could be a function that takes a function parameter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*J9SCdb6vffYGHaqJCTmnWA.png" /></figure><p>Now, this also means we can do Closures.</p><p><a href="https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c">All you need to know about Closures — The first pillar of Javascript.</a></p><p>Like objects in Javascript, closures are a mechanism to contain state.</p><p>In Javascript, we create a closure whenever a function accesses a variable that is outside of its immediate scope. We simply define a function inside another function and expose the inner function either by passing it or passing it to another function as a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*0Q2D2oaFdmmQvuAUCbHTvA.png" /></figure><p>Now I can give this to a variable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVtvZREeTYlRtV3SgvC1fA.png" /></figure><p>Now even though the initial <em>closure</em> function was called and we are done with that, because of closure, this <em>increment</em> function remembers the variable declared in the outer scope.</p><p>The variable used by the inner function will be available to it even after the outer function has finished running.<br>Here we are modifying state outside of our function. This increment function is touching state or data that belongs to another function — the closure function.</p><p>This however doesn’t mean that we can&#39;t use closures. They are very powerful. We just have to be careful. Closures only make a function impure if we modified the closed over variable.</p><p>For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKS1R028Wlr3Ogg1NP4QAA.png" /></figure><p>We are using closures here. Also, note that we are not modifying the state like we had before but we still have access to data outside of ourselves. As long as we don&#39;t modify and mutate that data, we are still following the functional programming paradigm.</p><p>Something important here is that we just created private variables. We are able to use closures to create data privacy which is very useful.</p><p>As a user, I can&#39;t modify <em>count=55</em>. Maybe it is an important variable that we shouldn’t touch. But because of closures, we still have access to that variable, and we are also making sure others don&#39;t modify it.</p><p>Closures get used a lot in functional programming for this specific reason; we just have to be careful not to modify the state.</p><h3>Currying</h3><p>This is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions each with a single argument.</p><p>You take a function that can take multiple parameters and instead, using currying, modify it into a function that takes one parameter at a time.</p><p>Let&#39;s look at an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*X6Ns3E5xH5o9ZTNhpIykog.png" /></figure><p>We can use currying here so that our function which takes multiple parameters at a time can take a parameter at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6yVsw--wBTsI9V5dpzl8vg.png" /></figure><p>Now because of closures, we have access inside of the <em>b</em> function to the <em>a </em>variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*QUU92ZwaiAa0RuoN1ZvwhA.png" /><figcaption>I am giving the function one parameter at a time.</figcaption></figure><p><strong>Why is this useful?</strong><br>Because now I can create multiple utility functions out of this. <br>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*bgrX-LJ1f8dmHMx5zQyGyA.png" /></figure><p>Now, I have called this function once and for the rest of its time is going to remember this piece of data forever until we finish running the program.</p><p>So that 10 years from now if we finally remember we have this <em>curriedMultiplyBy5,</em> I can use it to multiply anything we want by 5. Let&#39;s say 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*-rGdXm44FaxCoEqgsU-GnA.png" /></figure><p>Instead of running this function over and over, I have run it once and now this <em>curriedMultiplyBy5</em> is there for us to use.<br>So if its a function that gets called many times, we only run this part of the function: <em>(b) =&gt; a*b</em></p><p>And currying reminds you of those methods on prototypes shared amongst objects; they are trying to save on memory or at least reduce on the work that our computers have to do.</p><h3>Partial Application</h3><p>This gets confused with currying. It’s only slightly similar.</p><p>This is a way for us to partially apply a function. It’s a process of applying a function with a smaller number of parameters.</p><p>It means taking a function, applying some of its arguments into the function so it remembers those parameters. It uses closures to later on be called with the rest of the arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*KySpQt9raLF5WmPUrzaMqQ.png" /><figcaption>We can say that this code uses partial application; but what if we had 3 parameters?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*H1MK2yxJV9rsZd3ikMKRrw.png" /></figure><p>Partial application says I want to apply a portion of the parameters, for example, and then the next time I call that function, I wanna apply the rest of the arguments.</p><p>But let&#39;s see the curried version first. Here we would just add another parameter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*ITgSl_5B4pO6nD40YHHLdQ.png" /></figure><p>Partial application says no I want you to call the function once and then apply the rest of the arguments to it. That means on the second call I expect all the arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*2fkP0dyJ_pcJ8prXQzjmcg.png" /></figure><p>So now if I do <em>partialMultiplyBy5(), </em>we have <em>5 </em>bound to the first parameter using <em>bind().</em></p><p>Now if I do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*hwI0MHOzku4c0HlaIp2M-w.png" /></figure><p>I have partially applied a parameter — the <em>a </em>parameter<em> </em>and then I get to call the rest of the parameters <em>b </em>and<em> c</em>. That&#39;s the main difference between currying and partial application.</p><p>Partial application says on the second call I expect all the arguments. Currying says I expect one argument at a time.</p><h3>Caching</h3><p>This is a way of storing values so you can use them later on. Ideally, you can think of caching as a backpack that you can take to school.</p><p>Instead of going all the way home when you need something, like a pencil, you have a small box on your back that holds items that you need.</p><p>Caching is a way for us to speed up programs and hold some piece of data in an easily accessible box.</p><h4>Memoization</h4><p>Is a specific form of caching. It&#39;s used a lot in <a href="https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews/m2G1pAq0OO0#:~:text=Dynamic%20Programming%20(DP)%20is%20an,example%20of%20the%20Fibonacci%20numbers.">Dynamic programming</a>.</p><p>Let&#39;s say we have a function that says we want to <em>addto80</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*R5wljGC8D8gP1sBxFYLapA.png" /></figure><p>Now if I run this function again, I will have to go through the same steps to add n to 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*OljNlX4mNoMciJyqJWDgJQ.png" /></figure><p>We have done the calculation 3 times. But what if this function takes a really long time?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*4ucG6wbzktpNHXY_kc-e2w.png" /></figure><p>Every time we run this function, we will have to run <em>long time</em> 3 times. We go through the steps one by one even though we’ve done the same calculations.</p><p>Is there a way that we can optimize this?<br>This is where we can use caching and memoization.</p><p>Let&#39;s improve the above function by doing something different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*4mLNNZjq2ND2PYsRRYe2LA.png" /><figcaption>Simple property access is O(1) with a hash table.</figcaption></figure><p>The first time I run this function, I get <em>long time</em>. The first pass through went through the else part and did this calculation that hypothetically is going to take a <em>long time</em>.</p><p>This is a simple example but this could also be a calculation that takes a really long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ljfBq2elZ0_oK_-_wdQmg.png" /></figure><p>If I run this function, the first time around, we call <em>long time</em> and we calculate to 85 but the second time around because this value was in the <em>cache</em>, we didn&#39;t have to do this long calculation and we just returned it immediately.</p><h4>So what is <strong>memorization </strong>exactly?</h4><p>It is a specific form of caching that involves caching the return value of a function that is based on its parameters. If the parameter of the function doesn&#39;t change, then it is memoized.</p><p>It uses the cache because it has calculated the same thing before with the same parameters and will return the same version of the function. If the parameter changes, then it&#39;s going to calculate both times.</p><p>Memoization is simply a way to remember a solution to a subproblem so you don&#39;t have to calculate it again.</p><p>Let’s improve our memorized function</p><p>Ideally, we don&#39;t want to fill the cache in the global scope. It’s good practice if the cache lives inside the function and it&#39;s not polluting the global scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*Yjio3gsNfHYgk3Eu9n3pXQ.png" /></figure><p>The problem now is that we reset the cache every time the function gets called. So the cache becomes an empty object.</p><p>To get around this we can use <strong>closures</strong> in Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pc65bF37FAwYkQuHH6EhVg.png" /><figcaption>Our function remembers that the parameter has not changed. It’s going to check the cache and say I do not need to do that calculation I already have it.</figcaption></figure><p>Because of closures, we are able to access the <em>cache</em> inside of the outer function. This allows us to be very efficient with our code. In this sense, we use memorization to optimize our code.</p><h3>Compose and pipe</h3><p>This is the most powerful concept in FP.</p><p>Compose means that any sort of data transformation that we do should be obvious. It&#39;s kind of like a conveyor belt in a factory.</p><p>First, we have data that gets processed by a function that outputs some sort of data. This then gets processed by another function that outputs that data in a new form and so on and so forth.</p><p>Composability is a system design principle that deals with this relation of components. A highly comparable system provides components that can be selected and assembled in various combinations. This makes it easy to move pieces around to get the desired output based on user-specific requirements.</p><p>Let&#39;s say I want to do something using functional programming but I also want to do two things at a time.<br>Let&#39;s say we have a<strong> number -50</strong> that gets multiplied by<strong> 3</strong>. We also want to take the <strong>absolute number </strong>or remove any negative signs from it. This means that we want to do two things — two functions.</p><p>How can we compose them together like an assembly line at a factory?</p><p>Of course, there are a lot of libraries that let you compose like <a href="https://ramdajs.com/"><strong>Ramda</strong></a>. In Javascript, you can use <strong>compose()</strong>; not to say that it exists in Javascript, its just very common.</p><p>Let&#39;s build one on our own that allows us to <em>multiplyBy3</em> and also <em>take absolute. </em>In order to do that, I need to compose these two pieces of functionality.</p><p>Let’s define our own compose function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hibGowiZr2Ke3hcuVd6OEQ.png" /><figcaption>Our function will take the two functions(f, g) — multiplyBy3 &amp; makePositive that act on the data we have</figcaption></figure><p>Now let&#39;s define the two functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1Ft-WQ7E7XSI8umTBzBDw.png" /></figure><p>Now if I run this I get 150 because 50*3 is 150 and we make that an absolute number by removing the negative.</p><p>Using <strong>compose</strong>, we’ve created our own assembly line where we can compose different functions together.</p><p>Remember the definition, <br>Composability is a system design principle that deals with the relationship between components that can be selected and assembled in various combinations.</p><p>There is a lot of power here because now we can compose functions and build them together to add extra functionality. We take a piece of data, we take it through all these functions and then we finally have some sort of data that gets outputted.</p><p>All those functions are pure and all those functions are composable.</p><p>Compose is one of the most common functions you are going to see in a programming language. If you are using functional programming, you are definitely using compose.</p><h3>Pipe</h3><p>Pipe is the same thing as compose except instead of going from right to left, it goes left to right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*Wrpt6wes2quSzBKMOU26jA.png" /></figure><p>We just swap these around so that now with pipe the operations are different. <em>f</em> gets run first over the data. The first parameter that we’ve given compose (multiplyBy3) gets run first, and then <em>g</em> gets run over that data. Make positive gets run last.</p><p>For example,<br><strong>fn1(fn2(fn3</strong>(50)<strong>))</strong></p><p>With compose, this is what we can do</p><p>(fn1, fn2, fn3)(50)</p><p>We are saying I want you to evaluate this right to left.<br>Take the data then apply <em>function 3</em> to it. Whatever comes out of that, apply <em>function 2</em> to it; whatever comes out of that, apply function 1 to it.</p><p>Pipe is just the opposite</p><p><strong>pipe(fn3,fn2,fn1)(50)</strong></p><p>These two functions are going to have the same exact output because the functions are the same. They are used interchangeably. You can use whichever you prefer for your readability.</p><p>And that&#39;s the power of compose. We get tiny functions that are easy to test and we put them together to have powerful results.</p><h3>Arity</h3><p>This simply means the number of arguments a function takes.<br>If we look at the compose function, it has an arity of 2; <em>MultiplyBy3</em> has an arity of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Wrpt6wes2quSzBKMOU26jA.png" /></figure><p>Although it isn&#39;t a solid rule, in functional programming, it’s usually good practice to have a fewer number of parameters. The fewer the parameters, the easier it is to use a function.</p><p>You can do more flexible things and it makes functions more flexible.</p><p>We can use things like<em> currying</em> or something like <em>compose </em>and<em> pipe</em> and —compose these functions together.</p><p>The more parameters a function has, the harder it is to compose it with other functions. It doesn&#39;t mean its impossible, but it does become more difficult.</p><p>So when it comes to <strong>Arity</strong>, there is no hard right or wrong. But you may want to stick to one or two parameters.</p><h3>Why functional programming is so great?</h3><p>The separation of data and functions — or data and the effects that happen on that data.</p><p>Doing effects and logic at the same time, as in OOP may create side effects that cause a lot of bugs. If multiple things in your program handle some piece of data at the same time, that gets really complicated and it can cause many problems.</p><p>So the idea of keeping functions small and pure and comparable; doing one thing at a time and doing it well; immutability; the idea that a function takes inputs and returns outputs so that it can be used with other functions allows us to have a predictable program minimizing bugs because everything is so simple.</p><p>And as long as we are able to combine these little small functions together, we are able to create really complex programs.</p><blockquote>It doesn’t mean that functional programming is the answer to everything. But because of its nature, it works well with distributed systems — systems that have different machines all over the world working with each other; or parallelism where multiple things have to happen in parallel</blockquote><p>It doesn’t mean that functional programming is the answer to everything. But because of its nature, it works well with distributed systems — systems that have different machines all over the world working with each other; or parallelism where multiple things have to happen in parallel. These functions are pure so there are no strange bugs.</p><p>But it also depends on the problem you have. There are times when Object-oriented programming might be better. <br>You are building a fairly tale game and you have clear object characters in the game that have some sort of state and can interact with that state and others can interact with them as well.</p><p>Or you have an amazon shopping cart where there is clear data that needs to get processed.</p><p>In fact, let’s build an Amazon shopping cart to apply these principles of functional programming that we’ve learned so far.</p><p><strong>Functionality</strong></p><ol><li>Add Item to cart</li><li>Add 3% tax to an item in cart</li><li>Buy item</li><li>Empty cart</li></ol><p>These are the functions we are going to need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*dPVCgEoRejZQsjuC6GXgNg.png" /><figcaption>These are the functions that are going to affect the Data that we have — the user</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*MByGDmO3bG5RA_nnBcRDOw.png" /><figcaption>The user</figcaption></figure><p>Based on what we&#39;ve learned, we want to keep these functions pure. We are also applying a bunch of steps to the same data.</p><p>We can use something like compose to compose all these steps so that function <em>purchaseItem()</em> does all these things here.</p><p>But first, how would we approach this without compose?<br>Let&#39;s say we receive the <em>user</em> and<em> item </em>as parameters; we will return the user with the new item.</p><p>We know that we want to keep things immutable. We don&#39;t want to modify the user, so we will return a new object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKt1BThVwrI54qSuvJGl7w.png" /><figcaption>The third parameter is our purchased item.</figcaption></figure><p>Here Kim our <em>user</em> has purchased a laptop with a price of 344 and it&#39;s in their purchase history. <br>But that&#39;s not all because remember, we have to add a tax and all the other functions we saw. Maybe Kim wants to remove something from the cart. We are being too simplistic here.</p><p>So we need to compose these functions together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DizpcWdWv0k9Dwr8PbHgbg.png" /></figure><p>I have a factory called purchaseItem that takes the data — <em>user</em> and <em>item </em>and we are giving this data to all these functions above. So let&#39;s compose all these functions together.</p><p>Note that here we have more than two functions. This is part of the reason you should use a library like Ramda or Lodash to use compose because you don&#39;t need to implement this yourself. For now, let&#39;s do it for the purpose of learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecOcc0bH5okq8-eKWvF0Yw.png" /><figcaption>We are using the spread operator to get all the other arguments</figcaption></figure><p>Now let&#39;s define <em>purchaseItem</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*v49p6ZliX7Ywd1pGYzYsOQ.png" /><figcaption>reduce is a higher-order function. Purchase item receives a bunch of items and they are composed one by one</figcaption></figure><p>Here we&#39;ve built our own compose function that allows us to enter any number of parameters that we want into purchase item. Now we can compose these functions and act over the data we receive.</p><ol><li><strong>Add Item to cart</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*oOmTLzPToaK584ZFx7YauA.png" /><figcaption>We are copying the prev cart array so we don&#39;t mutate data. We are passing the item we are buying</figcaption></figure><h4>2. Apply Tax</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgZm5bTn9LI5h_nwZZy9UA.png" /><figcaption>If we run this we see that the price of the laptop went up from 200 to 260. We successfully applied a tax</figcaption></figure><h4>Buy Item</h4><p>Here we want to move the cart item to purchases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bVnNufh6Vzbv8zLMuQTOA.png" /></figure><h4>Empty cart</h4><p>So now that Kim has purchased her item, we want to empty that cart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyyqOjnwstRR3oFgE0KCOA.png" /></figure><p><strong>Kim </strong>has just purchased her first laptop.</p><p>Everything just works like a factory. And if we want to add new functionality such as upgrade <strong>Kim’s</strong> status, the rest of the code doesn&#39;t really care about that — we can just create a new function and just add it here.</p><p>That&#39;s the beauty of functional programming.</p><p>It’s the idea that we are building these small comparable functions that are each worried about their own world. So that whenever bugs happen, as long as they are tested well, it&#39;s most likely that the bug is in a place where we might have <strong>state. </strong>The rest of the functions are pure.</p><p>But here is the exciting part that makes functional programming so interesting. We can playback history as well.</p><p>As a retailer, you want to keep track of your data. You want to know what users did. So you need a way to figure out what happened — perhaps logs of what the user might have done that may have resulted in an error.</p><p>Using our functional programming paradigm, we have the ability to travel back and forth through time.<br>We can have a history variable that we can fill up at every stage.</p><p><strong>let amazonHistory = [];</strong></p><p>Now every time we do something, we want to add to this history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*vQzTDMBgYWYvABnp27Irlw.png" /><figcaption>In <em>addItemToCart, we are pushing the user’s </em>current state.</figcaption></figure><p>So that when I run <em>amazonHistory, </em>I have the entire history of <em>Kim </em>and what she did. We can go back in time now and see where Kim made her purchases.</p><p>Maybe now Amazon can create new functions like <em>getUserState()</em> or go back in <em>history()</em> or <em>goforward(). </em>The possibilities are endless.</p><p>And although we are modifying state with <em>amazonHistory</em>, remember we can’t have pure functions alone. At some point, we do have to mutate data. The idea here with functional programming is to minimize those mutations.</p><h4>Pipe</h4><p>Remember <em>compose</em>, we go from right to left. If you prefer reading from left to right, you just change <em>compose</em> to<em> pipe</em> and just change <em>g </em>into <em>f </em>and<em> f</em> into <em>g</em>.</p><p>We will have to change the orders of the functions as well in the opposite direction. You can choose pipe and compose based on what you like.</p><h4>Conclusion</h4><p>Functional programming gives us this idea of a pure function; and functions are useful because we limit repetitions. The beauty is that now every time we use a function, we can reuse it somewhere else.</p><blockquote>Functional programming lays the foundation for creating reusable code. We can move pieces of functions around to do different things based on our needs.</blockquote><p>Functional programming lays the foundation for creating reusable code. We can move pieces of functions around to do different things based on our needs.</p><p>And although functional programming has different concepts than OOP, at the end of the day, the goal is still the same; we want our code to be:</p><ol><li>Clear + Understandable</li><li>Easy to extend</li><li>Easy to maintain</li><li>Memory efficient</li><li>DRY</li></ol><h4>Composition vs Inheritance</h4><p><strong>Inheritance</strong> is a superclass that is extended to smaller pieces that add or overwrite things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*hC9EVNxZvlYzzDwF.png" /><figcaption>Here Elf uses inheritance by using “class extends “</figcaption></figure><p><strong>Composition</strong> on the other hand is when we use smaller pieces to create something bigger. We compose functions to act on data differently.</p><p>Let&#39;s see how composition can solve some of the problems that come with inheritance. Keep in mind that the idea is not to pick one over the other.</p><p>You can use both.</p><p><strong>Drawbacks of inheritance.<br></strong>With inheritance, code is structured as <em>what is</em> vs<em> what it has </em>in functional programming.</p><p>With classes, we say that a class will have data, properties, and methods that act upon that data.</p><p>But when we define things as<em> what they are</em>, it becomes very hard to be able to change them. With inheritance, we are assuming no change yet things change all the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*tl4uPXhGYRhN8gzF.png" /></figure><p>For example, let&#39;s say that from the above example, the character needs to have a sleep method added to it. Now all the classes that extend from character will have the sleep method even though they don’t necessarily need it.</p><h4>Tight coupling problem</h4><p>With a parent class and a child class, the coupling is very tight.</p><p>Its the opposite of reusable modular code. Making a small change to a class has a rippling effect on all its subclasses and this tends to break things.</p><p>So a tightly coupled inheritance where you can change things in one place and will have rippling effects to all the other things can be a benefit where you keep your code DRY but it can also cause a lot of problems.</p><p>With dependencies, if you change something on a class, you have to make sure that it doesn&#39;t break anything in its subclasses because they are using inheritance.</p><h4><a href="https://en.wikipedia.org/wiki/Fragile_base_class">Fragile base class problem</a></h4><p>Because the base class changes all subclasses, this can be very fragile. It can break our code down the path.</p><p>“‘fragile’ because seemingly safe modifications to a base class, when inherited by the <a href="https://en.wikipedia.org/wiki/Subclass_(computer_science)">derived classes</a>, may cause the derived classes to malfunction. The programmer cannot determine whether a base class change is safe simply by examining in isolation the methods of the base class”.</p><h4>Hierarchy problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*k4eMD4-LG7ZS6q7u.png" /></figure><p>If there were two Elves — <strong>boss Elf</strong> and <strong>Junior Elf</strong> and the junior elf inherits from a boss elf. The problem with hierarchy is that now what if the junior elf is higher up in hierarchy for some reason than the boss elf?</p><p>And if we have more methods it means the junior elf is also going to inherit all the methods that it doesn&#39;t need. This is also know as the classic <a href="https://www.johndcook.com/blog/2011/07/19/you-wanted-banana/">gorilla banana problem.</a></p><p>So how can we fix some of these bad inheritance principles with composition?</p><p>For starters, we can remove all the methods and compose them separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*DYL8X211S5cadimUSke_sg.png" /></figure><p>Here we are saying that these are the abilities that the Elf has. We have the bearest Elf character possible and we can continue adding abilities to it.</p><p>We are turning the inheritance model from what an Elf is to what an Elf does. By having a base Elf, we give the Elf abilities through things like <em>getAttack() </em>which uses functions to add to the character object different abilities. Now we can compose these small little pieces of functionality to describe our character.</p><p>Also here state is not internal; <em>getAttack </em>simply gets the character state and returns it, same with Elf.</p><h4>So to review,</h4><p>Inheritance is a superclass that is extended to smaller pieces that add or overwrite things. <br>And although you can be very careful with it and make sure that the base class is very general, so that we don&#39;t overload our subclasses, it can easily get out of hand as we go deeper and deeper down the inheritance chain.</p><p>And once we need to change something, it becomes really difficult. On the other hand, composition is about smaller pieces that are combined to create something bigger. We combine these boxes based on what we need to create our desired output.</p><p>And if we need to add something later on, we just add another puzzle by composing things together or even remove them if we don&#39;t need them anymore.</p><p>So arguably composition is a better solution long term than inheritance but this doesn&#39;t mean that inheritance is always bad. There are ways that you can still write great programs with inheritance but with problems that might come up in the future especially with so many unknowns, it becomes really difficult.</p><p>Composition will help us create code that is more stable as well as easier to change in the future — its simply a better tool to use when creating software.</p><p>A programming paradigm is writing code compliant with a specific set of rules. For example, organizing code into units would be called OOP and avoiding side effects as well as writing pure functions would be called FP.</p><p>In OOP, an object is a box containing information and operations that are supposed to refer to the same concept or grouping it as an object. These pieces of information inside the object are called attributes or state and the operations that can happen on the state are known as methods.</p><p>In functional programming, the code is essentially a combination of functions and data is immutable; this leads to writing programs with no side effects.</p><p>A pure function cannot change the outside world and the output value of a function depends on the given arguments. This allows functional programming to have real control over the program flow.</p><p>In functional programming, functions are first-class citizens whereas in OOP, objects are first-class citizens.</p><p>We also saw the pillars of each of these paradigms. <br>In OOP, we had Abstraction, Encapsulation, where it allows us to encapsulate ideas that are related together in objects. We hide irrelevant data from the user. We learned about inheritance and polymorphism.</p><p>In FP, we saw that it&#39;s all about the idea of pure functions and composing functions to act upon that data.</p><p>Both these paradigms have been around since the 70s.</p><p>OOP is very common in languages such as C sharp, Python, Java, and FP in languages such as closure and Huskel.</p><p>But at the end of the day, we are not choosing one over the other. All of them are good in their own ways. They are simply different approaches to the same problem.</p><p>Although some languages prefer one over the other in terms of programming paradigms, however, languages like Javascript allow you to do both.</p><p>The advantage of each paradigm is in the way you model your algorithm and data structures, the choice is simply what makes more sense for your project</p><h4>Key differences</h4><p>FP is all about performing many different operations for which the data is fixed.</p><p>OOP is about few operations on common data.</p><p>In FP, we don&#39;t modify state.</p><p>OOP is very stateful.</p><p>FP functions are pure; there are no side effects. The functions we write don&#39;t make an impact on the code that is running outside of that function.</p><p>In OOP there are side effects; methods manipulate our internal state.</p><p>FP is more declarative. It&#39;s about what we want to be doing</p><p>OOP is about how we want it to be done which is more imperative.</p><h4>So when should you use one over the other?</h4><p>FP is quite good at processing data for large applications. If you are analyzing user data, maybe using it for a machine learning model, Functional programming works well for high performance in processors and because you can run it on multiple processors.</p><p>If on the other hand you have many things like characters in a game, with not too many operations, then OOP might be a better solution.</p><p>But you can use the ideas from both of these to write your code. For example, the<strong> react javascript framework</strong>, uses both classes and pure functions</p><p>In all programs, there are two primary components:<br>The data and behavior.</p><p>OOP says, bring together the data and the behavior in a single location called object or class. It’s gonna allow us to understand our program easier and be more organized.</p><p>Functional programming says that data and behavior and distinctly different things and should be kept separate for clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a87629ecaed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-comprehensive-look-at-functional-programming-fp-4a87629ecaed">A Comprehensive Look at Functional Programming (FP)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A comprehensive look at Object-Oriented Programming(OOP)]]></title>
            <link>https://blog.devgenius.io/a-comprehensive-look-at-object-oriented-programming-oop-91d6423dde9a?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d6423dde9a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[myjavascriptjourney]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 03:18:18 GMT</pubDate>
            <atom:updated>2020-06-24T07:57:26.963Z</atom:updated>
            <content:encoded><![CDATA[<h4>A programming paradigm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR2SzZLe1QHRTbTLRDfLZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@badshah05?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hussain Badshah</a> on <a href="https://medium.com/s/photos/chains?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Here is what to expect from this article:<br>1. The <strong>this </strong>keyword<br>2. The<strong> new</strong> keyword<br>3. All about<strong> prototype</strong> <br>4. <strong>ES6 classes</strong><br>5. Class-based languages like <strong>Java </strong>and<strong> C++</strong><br>6. <strong>Inheritance</strong><br>7. <strong>Object.create</strong><br>8. <strong>Private </strong>vs<strong> Public</strong><br>9. The <strong>4 principles of OOP</strong></p><p>A programming paradigm allows us to organize code in a way that is easy to reason about.</p><p>This is what we hope to get from understanding this programming paradigm:</p><ol><li>We will make code more clear and more understandable.</li><li>We will make our code easy to extend. Remember, as our app grows, and as our programs grow, as the developers on the team grow, our code is easier to extend using these programming paradigms.</li><li>Make code easier to maintain by multiple programmers.</li><li>Make our code memory efficient.</li><li>It will keep our code DRY. We won’t repeat ourselves. Our code will be clean and efficient.</li></ol><p>So it&#39;s clear that programming paradigms allow us to make complex code more organized. But before OOP and Functional programming, there was machine code; initially, it was all ones and zeroes that programmers used.</p><blockquote>A programming paradigm allows us to organize code in a way that is easy to reason about.</blockquote><p>As time passed, we went into a <a href="https://en.wikipedia.org/wiki/Procedural_programming#:~:text=The%20focus%20of%20procedural%20programming,members%20or%20attributes)%20using%20interfaces.">procedural style of programming</a>. With this style, we did what computers wanted us to do — that is we would store data and then manipulate this data using some sort of functions. But there was no structure or organization.</p><p>We just had step by step instructions: <em>Computer, put memory here, computer move this memory here, computer change memory here and then give me this.</em> Everything was <strong>procedural</strong>.</p><p><a href="https://en.wikipedia.org/wiki/History_of_programming_languages">History of programming languages - Wikipedia</a></p><p>Initially, we started with basic programming languages — really low-level languages. <strong>Basic</strong>, <strong>Assembly language</strong>,<strong> COBOL</strong>, but throughout the 60s and 70s, a big change happened. We started establishing these fundamental paradigms.</p><h4>How can you write code in a more organized fashion?</h4><p>Code that isn&#39;t procedural. That&#39;s when<strong> OOP</strong> and <strong>FP</strong> started to take effect. We had languages like <a href="https://en.wikipedia.org/wiki/Scheme_(programming_language)#:~:text=Scheme%20is%20a%20minimalist%20dialect,by%20its%20developers%2C%20Guy%20L.">Scheme</a> which was one of the inspirations of Javascript. We had languages like <a href="https://en.wikipedia.org/wiki/Smalltalk">Smalltalk</a> which popularised this idea of<strong> OOP</strong> as a way to organize code.</p><p>And finally, in the 80s as more and more best practices started to happen, we started to have more of a consolidation — people agreeing on what some good patterns and best practices are. Things like modules.</p><p>Here, <strong>OOP</strong> really started taking off. We had languages like <a href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a> that came into existence. C++ was the original <a href="https://en.wikipedia.org/wiki/C_(programming_language)#:~:text=C%20(%2Fsi%CB%90%2F%2C,efficiently%20to%20typical%20machine%20instructions.">C</a> language with classes — classes that allowed us to do <strong>OOP</strong>. We had <a href="https://en.wikipedia.org/wiki/Objective-C">Objective C</a> and as the name suggests, it was a C based language that was inspired by the idea of objects and <strong>OOP</strong>. And that&#39;s when things really started to take off.</p><p>At the same time in the background, we also had functional programming. In the 90s, with the age of the internet, we started having more languages. Java became a hit with its <strong>Object-Oriented Paradigm.</strong></p><p>In 1995, we had Javascript that came as the language of the web and many other languages that we are familiar with.<strong> OOP</strong> kept up with the trends and it was really popularised with languages such as Java.</p><p>Today, we now see a trend towards Functional programming languages. They are becoming more and more popular, mostly because of the way the paradigm works well with <a href="https://en.wikipedia.org/wiki/Concurrent_computing">Concurrent </a>and <a href="https://en.wikipedia.org/wiki/Distributed_computing#:~:text=A%20computer%20program%20that%20runs,like%20connectors%20and%20message%20queues.">Distributed programming</a>.</p><blockquote>This all shows that as the years progressed, programmers as we work more and more with code, we start to develop ideas of what we deem good practices.</blockquote><p>This all shows that as the years progressed, programmers as we work more and more with code, we start to develop ideas of what we deem good practices. <br>So people then were asking themselves what should we do? <br>And OOP and FP were the two strong paradigms that evolved. And so by learning these two things, we get to stand on the shoulders of giants.</p><p>We get to know what are the good practices that all these programmers that came before learned, the mistakes that they made, and in so doing, we write better code.</p><h3>Object-orient programming Vs Functional programming</h3><p>In all programs, there are two primary components:<br> 1. The Data — stuff we keep on our memory.<br>2. The behavior — the things that programs can do.</p><p>In order for us to deal with these two things, we initially had languages like Java and Scheme that had different ideas of what we can do(Java and Scheme were the inspiration of Javascript).</p><p>We previously learned that there are things like functions and objects in Javascript and that they are really important. We learned all about <strong>Prototypal inheritance, </strong>about functions, and their useful tools like<strong> Closures</strong> and the idea that functions were first-class citizens in Javascript.</p><ul><li><a href="https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c">All you need to know about Closures — The first pillar of Javascript.</a></li><li><a href="https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509">All you need to know about Prototypal Inheritance — The second pillar of Javascript</a></li></ul><p>From these two ideas, we had Functional programming and Object-oriented programming.</p><p><strong>OOP</strong> says bring together the data and it’s behavior in a single location called an object; putting all this in a box makes it easier to understand how our programs work.</p><p>Functional programming says that data and behavior are distinctly different things and should be kept separate for clarity. So perhaps instead of having one giant box to describe everything, we have multiple boxes.</p><p><strong>OOP</strong> is like building a robot, we have a head component, a hand component, maybe a chest component, legs component, antennae component and we build those together.</p><p>Functional programming says just give me data and I will act upon that data through functions and I will return something new from the data that you gave me.</p><p>The goal here is not to show you that it&#39;s <strong>FP </strong>Vs <strong>OOP</strong> but rather that these are actually complementary. It&#39;s not one over the other. Instead, it&#39;s about using both paradigms in unison to make good programs. The beauty of Javascript is that it&#39;s multi-paradigm.</p><p>We can use both these techniques to make our code easy to reason about, to make it clearer, to make it understandable, easy to extend, and more efficient. Also, we can use each of these paradigms based on the problems at hand and use the techniques in each to pick a paradigm for a specific problem.</p><p>The <a href="https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509">two pillars</a> finally allow us to learn about these topics.</p><p><a href="https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c">Closures</a> are a big part of <strong>FP </strong>and without them, we wouldn&#39;t be able to do what I am going to show you with Functional programming. And without Prototypes, we are not going to be able to do the things that we are going to do in <strong>OOP</strong>.</p><h3>OOP introduction</h3><p>Most of the stuff here, we have already seen. <br>The<a href="https://medium.com/@allansendagi/javascript-fundamentals-this-keyword-481722806d20"> <strong>this</strong></a><strong> </strong>keyword, <a href="https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509">prototypal inheritance</a>, the<strong> new</strong> keyword, the new <strong>ES6 classes</strong>,<strong> inheritance</strong>, <strong>Object.create</strong>. <br>We are also going to see private and public fields — the idea of class-based inheritance in languages like Java. And finally, we will cover the four principles of OOP.</p><h4>OOP has been around since the 70s.</h4><p>It’s a style of programming that is very common in languages such as <a href="https://en.wikipedia.org/wiki/C_Sharp_(programming_language)">C#</a>, Python, Ruby, and Java. In OOP, an object is a box containing information and operations that are supposed to refer to the same concept.</p><p>It&#39;s like we are modeling real-life objects. And we’ve seen this before with our dragon object. We had some OOP principles here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*04kh3-ziwyHRQCkf.png" /></figure><p>We had data about the dragon such as <strong>name</strong> and the ability to breathe fire. We also had actions that the dragon can take. In OOP, this data can also be called state. <br>We’ve wrapped this dragon in an object to model a real-life dragon that contains some data about the dragon, and also the actions that the dragon can take.</p><blockquote>The attributes or properties allow us to keep track of the state of the object and the methods allow us to manipulate the state of the object so that we model the real world.</blockquote><p>The attributes or properties allow us to keep track of the state of the object and the methods allow us to manipulate the state of the object so that we model the real world.</p><p>And that&#39;s what we want to do with <strong>OOP</strong>.</p><p>We want to look at the world and organize the things we want to do into these small little object boxes that interact with each other. So that we keep everything divided and organized.</p><p>When it comes to OOP, there are two main types:<br>1. There are class-based programming languages.<br>2. Prototype-based programming languages.</p><p>As we know with Javascript, we have Prototypal inheritance. So let&#39;s look at the whole journey from procedural code — code that we repeat ourselves into code that goes all the way to <strong>OOP</strong>.</p><p>Let&#39;s start with a game that has characters that interact with each other. using Let&#39;s create a program that has <strong>OOP</strong> principles in mind to organize our code.</p><p><strong>Creating an elf object</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*4J7dyA5Cx5IVh-cxoQWb4w.png" /><figcaption>The elf character. source: ZTM</figcaption></figure><p>As with any game, we are not going to have just one elf. We are going to have different elves with different names, different weapons, maybe even different methods. <br>So what should we do if we want to add another elf?</p><p>We can copy and paste this code and maybe create elf2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*KVa_qR4vtsjs1cL_6yvEcQ.png" /><figcaption>The second elf character in our game</figcaption></figure><p>So what&#39;s the benefit of what we have just done that has moved us towards OOP?</p><p>We have something called <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">Encapsulation </a>here. We’ve grouped functionality together. We have state — that is data within the object and functions acting on that state. <br>So that these functions can interact with this state. They can read it or even modify it. We can have a method that maybe changes weapon from let&#39;s say bow to the sword.</p><h3>This is our first step towards OOP.</h3><p>We’ve encapsulated functionality that can be contained to model real-world elves into these containers. But what&#39;s the problem with this?</p><p>The clear problem is that when we need more elves — which in this game we are going to need a lot of them, we have to copy the same code over and over even though the elves have the same attack method. We have to repeatedly copy and paste code all the time.</p><p>And most likely, we have way more functionality than this for our elves which would mean way more properties, way more methods. We are not keeping our code very DRY. We are just constantly repeating ourselves.</p><h3>So let&#39;s move on to step two towards OOP.</h3><h4>Factory Functions</h4><p>Factory functions are functions that act like factories — they create objects for us.</p><p>Let’s programmatically create elves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*p10avhTLf318fosVvsEQWQ.png" /></figure><p>Here we have created a factory function — a function that creates objects for us. And we can even simplify this using ES6 syntax where if property and value are the same, we can just keep it inside of an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*956jcuQVXxWOnf55BAZXqA.png" /></figure><p>The beauty with factory functions is that now if I want to create another elf, all I do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIc5d0064RHEo7lMcctO0w.png" /></figure><p>So instead of just copying code, we now have this function that just creates elves for us.</p><p>We’ve moved up a step towards <strong>OOP</strong>.</p><p>We avoided repetitive code. But there is still a problem here. Factory functions are great but what&#39;s wrong here?<br>What if we have 1000 elves? It means all 1000 elves require space in our memory to store the same data!</p><p>So things like <strong>name</strong> and <strong>weapon </strong>are going to be different and we are going to have to store that data in memory for each elf. Also, methods such as<strong> attack()</strong> that are pretty generic have to be copied unto memory in a different location for each of these elves.<br>So if we had 1000 elves, that&#39;s 1000 attack functions in different places in memory for each elf.</p><p>Luckily, Javascript has this thing called <strong>Prototype inheritance</strong>. We can use that to our advantage to improve this so that we share functionality across different objects.</p><p><a href="https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509">All you need to know about Prototypal Inheritance — The second pillar of Javascript</a></p><h3>So let’s move on to step three towards OOP.</h3><p>We want to solve this issue of having the same functionality on multiple objects. How can we do that?</p><p>Before we get to prototypal inheritance, there is one way of going about this manually.</p><p>We can take out the <strong>attack</strong> function, and place it in some sort of a store where we have common functionality. For example, I can do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*d-TfOYiBGPXE-5WpB0TylA.png" /></figure><p>Now I have a simple object that has the attack method on it and all I need to do now to give the attack ability to Peter and Sam is to add a line of code that says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*7noTz08XMA43QoDTxDgyKw.png" /><figcaption>peter.attack()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*klQkSxp9kGJSzS1cMnsPJw.png" /><figcaption>Sam.attack()</figcaption></figure><h3>Object.create()</h3><p>This works but it’s still a lot of manual work. Javascript gives us a tool to make this easier on ourselves. We can use <strong>Object.create()</strong>.</p><p>With Object.create(), I can clean this up a bit. Instead of manually having to attach the methods onto each elf, we will remove our lines of code and use Object.create() to create that link — that prototype chain between these two parts of the code.</p><p>And we can do that fairly simply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*euLs3y_j69Qk6XMyl7nWag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*WBA2CUf0Py149JR0N9CgDA.png" /></figure><blockquote>What Object.create does is it creates a link between the <strong>elf functions </strong>and the <strong>newElf</strong> that we just created. We are doing Prototypal inheritance here.</blockquote><p>What Object.create does is it creates a link between the <strong>elf functions </strong>and the <strong>newElf</strong> that we just created. We are doing Prototypal inheritance here.</p><p>Object.create creates this prototype chain for us all the way up so that we can use the attack method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30zr3Zm0tBjIRI75Ue68Pg.png" /></figure><p>Here is one problem. You won’t see this out in most code bases even though what we are doing with <strong>Object.create() </strong>is true prototypal inheritance. It’s meant to be used like this.</p><p>It&#39;s true our code is a little cleaner but this is not very accepted by the Javascript community as a whole.</p><p>Our goal is to get closer to Object-oriented programming. But what we are doing here isn&#39;t necessarily OOP yet.</p><p>So what did programmers use before Object.create()?</p><h3>Step four towards OOP.</h3><p>Without Object.create we did something that is even closer to OOP. Instead of using Object.create(), we were using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor#:~:text=The%20constructor%20property%20returns%20a,true%20%2C%20and%20%22test%22%20."><strong>Constructor functions</strong>.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*1nHzC6mqZnAH3CkI125yxQ.png" /></figure><p>Here is the interesting part; I am not returning anything here. I am using <a href="https://medium.com/@allansendagi/javascript-fundamentals-this-keyword-481722806d20"><strong>this </strong></a>and that&#39;s it.</p><h4>We are constructing an elf.</h4><p>So how does this work?</p><p>Now if I do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFEqKUzPauGLSo6RIzUepg.png" /><figcaption>If I run this, I get a type error — <em>cannot read property ‘name’ of undefined.</em></figcaption></figure><p>If I run this, I get a type error — <em>cannot read property ‘name’ of undefined.</em></p><p>And this is because Constructor functions are built like this: In order to use the constructor function, you need to use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><strong>new</strong></a> keyword in Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elIY_krvy__7s_XN0WTl0A.png" /></figure><p>We see that magically works. But why is that?<br>That is because the new keyword in Javascript automatically returns the object for us and creates the elf constructor.</p><blockquote>Any function that is invoked using the <strong>new</strong> keyword is called a constructor function.</blockquote><p>Any function that is invoked using the <strong>new</strong> keyword is called a constructor function.</p><p>And we’ve seen constructor functions before. Things like<strong> Number()</strong>,<strong> Object()</strong> or<strong> Function()</strong> — capital letters but they were functions.</p><p>Those were all constructor functions. You invoke them by using the <strong>new</strong> keyword. So as a rule, all constructor functions should start with a capital letter to let other programmers know that you need to call this function using the new keyword.</p><p>Let&#39;s see how we can create an elf using the constructor Function that comes natively in Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVfMDuLwlrqWDXEBpgbjrQ.png" /></figure><p>Function constructors simply allow us to use the <strong>new</strong> keyword and create these objects for us.</p><p>But now let&#39;s implement the attack function here.</p><p>Since we have used the <strong>new</strong> keyword which automatically returns an Elf object for us and creates our Elf constructor Function, we’ve created a new object. And because this function is called, a new execution context is created.</p><p>And since this is a function that we are running — <strong>Elf</strong>, and a new execution context is created, that means we automatically get the <strong>this</strong> variable attached to it. Remember that every function that we call gets <strong>this</strong> and the arguments parameters.</p><p><a href="https://medium.com/@allansendagi/javascript-foundation-function-invocation-arguments-keyword-variable-environment-scope-chain-97d4888cf319">Javascript Foundation — Function Invocation, Arguments keyword, Variable environment, Scope chain.</a></p><p>Interestingly here when we use the <strong>new</strong> keyword, instead of <strong>this</strong> pointing to the window object, like it usually does, the <strong>new </strong>keyword changes what <strong>this</strong> is pointing to when a new execution context is created. Instead, the <strong>new </strong>keyword will say, I want you to point <strong>this</strong> to the object that we just created. So that this becomes <strong>Peter.</strong></p><p>Let&#39;s see what happens when we remove the <strong>new </strong>keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiRYSdTw76pGKAVf3IxZeQ.png" /><figcaption>Removing the new keyword</figcaption></figure><p>That&#39;s because without the<strong> new</strong> keyword, we are not returning that object and we are also not assigning <strong>this</strong> to the object that calls us.</p><p>So the <strong>new</strong> keyword does a lot for us behind the scenes in order for this to work.<br>So it&#39;s very important that we use the <strong>new</strong> keyword which is why we want to use capital letters to indicate to other programmers that we need to use the <strong>new</strong> keyword otherwise it&#39;s not going to work.</p><blockquote>The reason this is so powerful is that every function in Javascript gets a prototype property.</blockquote><p>The reason this is so powerful is that every function in Javascript gets a prototype property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*w7tBjCPJrytmVX92.png" /></figure><p>A Function is a special type of object. It&#39;s a callable object that has code that can be invoked, an optional name, properties that in case we want to give it, we have access to.</p><p>But we also get the prototype{} that&#39;s created with every new function. This prototype property is absolutely useless with any regular function but when we have constructor functions, this prototype finally becomes useful. Native constructor functions like <strong>Function</strong> come with things like call, apply, and bind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*JZ1Zfb8VFjP2IKy0.png" /></figure><p>Arrays come with <strong>reduce</strong>, <strong>map</strong>, <strong>forEach</strong> because they are built out of the Array constructor function.</p><h4>In our case, we can add our own to the prototype.</h4><p>So now we can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*1hSMivnqiQbIgOPucoUnsA.png" /></figure><p>And we are able to use the <strong>Prototype</strong> to add functionality to our Elf.</p><p>To review,</p><p>We are able to use constructor functions instead of something like <strong>Object.create()</strong> to create this magical function. Our magical function returns a new function and modifies what <strong>this</strong> means to whatever object calls us. So instead of the global object, <strong>this</strong> is now going to point to the calling object; <strong>Peter </strong>and <strong>Sam</strong>.</p><p>Also, since this is a constructor function, we have the Prototype function that we can attach things to.</p><p>So that when <strong>Peter.attack()</strong> gets called, it works. Remember, Peter doesn&#39;t have <strong>attack()</strong> as its own method but it&#39;s going to go up the Prototype chain where it&#39;s going to find attack.</p><p>Now both <strong>Peter</strong> and<strong> Sam</strong> are able to use <strong>attack()</strong> from the same location in memory. Instead of us copying <strong>attack()</strong> in multiple places in memory, we just have it written once and both these Elves are going to point to the same memory space.</p><p>And the beauty is I can just keep adding functionality or methods as the game evolves.</p><p><strong>Note:</strong> What happens if we change this to an arrow function?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRZWQW0tG1nArZClOUmXHg.png" /></figure><p>We get undefined.</p><p>Remember, arrow functions are lexically scoped. They define <strong>this</strong> based on where they are written. And <strong>this </strong>in this case is the global object because who is calling <strong>this</strong>, there is no Object surrounding it other than the global object.</p><p>But by using the regular function, which is dynamically scoped,<strong> this</strong> is going to change based on who calls it. This one area where you don&#39;t want to use arrow functions because you don&#39;t want a lexically scoped <strong>this</strong>.</p><h4>Let&#39;s dig deeper on the constructor functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLQmdx7b_ke3IcgKQ7FsIw.png" /><figcaption>console.log(<strong>this</strong>) gives us Elf as an empty object</figcaption></figure><p>Since there are no properties here because we haven&#39;t added anything, we just create an empty object.</p><p>But if I move <strong><em>console.log(this)</em></strong> down, we see that after we add the <strong>name </strong>and<strong> weapon</strong> properties, we have them accessible to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*Fu0_0klcHjHEKfZ3fVIGSg.png" /><figcaption>demonstrating <strong>this</strong></figcaption></figure><p>What&#39;s interesting is that now if I add a <strong>var q=6</strong> to our constructor function, we won&#39;t be able to add it to our elf object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*PACnngmU-EhTsTFEUrNBCg.png" /><figcaption>We can only add properties to Elf using<strong> this</strong> keyword</figcaption></figure><p>With a constructor function, the only way we can add properties to the object is by using the <strong>this</strong> keyword.</p><p>We also talked about how constructor functions automatically create that prototype chain for us. So let&#39;s test that out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*q0XrZg1aidPQ-6JK8wOChQ.png" /></figure><p>We see that we have Elf as our prototype because<strong>__proto__</strong> points to the prototype of Elf. Remember,<strong> Elf.prototype</strong> was created for us because of the <strong>new </strong>keyword.</p><p>So that when we finally add onto the prototype an item like <strong>attack()</strong>, we now have <strong>__Proto__ </strong>pointing to <strong>Elf.prototype</strong> which contains the<strong> attack()</strong> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hceq3FikqfuZJYP1Xdhksw.png" /><figcaption>peter__proto__ points to Elf prototype</figcaption></figure><p>Now if I do<strong> Elf.prototype</strong>, we see that it’s the same thing. We have the <strong>attack()</strong> function inside of this prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*WzhT7OhDoHyj5lA3yNl5TQ.png" /></figure><p>If we console.log before we add the prototype:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*3nQnof4mCMUq4B_UG974Yw.png" /><figcaption>It’s an empty object</figcaption></figure><p>Remember that every function that we create gets this prototype property. But only<strong> Constructor</strong> functions have use for this prototype Object.</p><p>But now what happens If I do <strong>Peter.prototype</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*G8NUFBdCns5b0TRGNWmVUw.png" /><figcaption>peter.prototype gives us undefined</figcaption></figure><p>I get undefined. This is because <strong>Peter</strong> is not a function. <strong>Peter</strong> is an object. Only functions have access to the prototype.</p><p><strong>Note:</strong><br>One of the gotchas in OOP is something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*t2JBGouo3yAW4fo1GFWQ-Q.png" /><figcaption>A function inside of a method is still a function inside a function</figcaption></figure><p>Here if I click run, I get<strong> undefined</strong>.</p><p>By why is that?<br>A Function inside of a method is a function inside of a function. This means that <strong>this</strong> is not assigned to the object itself but this time to the window Object. There are a few ways to solve this:</p><h3>bind()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*AaavU5lkzM1eVI30Ikgx4Q.png" /></figure><p>Or we can just have a reference to <strong>this</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*1Xd59KT2rpofrALW2mKYGA.png" /></figure><h3>So are we there yet? Or what is the problem with this code?</h3><p>The problem with this code is <strong>prototype</strong> is kinda weird. It’s a little hard to understand, isn&#39;t it?</p><p>This code is not easy to understand unless you really know your prototype inheritance and how Javascript works, which most people don&#39;t. This can get very confusing very fast. Not many people like this style of coding.</p><p>In older codebases, you might find this style of programing especially if they are doing OOP. The problem is OOP is all about the idea of classes. With this code, there are no classes in here and the capital letter thing which is why<strong> Object.create()</strong> was added to the language in order to avoid this headache and just use pure prototypal inheritance. <br>But the idea of <strong>this</strong> and the <strong>new</strong> keyword is very much OOP inspired especially when it comes to languages like Java.</p><h3>The final step to OOP with Javascript.</h3><p>So how can we improve this? Let&#39;s add classes and get as closer as we can to OOP with Javascript.</p><h4>Everything in Javascript is an object.</h4><p>Let&#39;s try something. We now understand constructor functions. So if I do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUragQGQxLBDkCwatVSZHQ.png" /></figure><p>Javascript creates<strong> Number 5</strong> for us.</p><p>And its a type of Object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*pXIC35_9adKz0BdmXAgh0A.png" /><figcaption>a is a typeof Object because we have used a constructor function</figcaption></figure><p>This is not the same as simply saying:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*ls_tBU-DW6MTUkSgi18byg.png" /><figcaption>typeof b is a number</figcaption></figure><p>And so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Zeaad4PfU2l-rFnzYiXxwg.png" /></figure><p>What we are seeing is that there are two different ways of constructing these things in Javascript.</p><p>However, if I just do two equal signs I get true because of type coercion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*qy6oZOIPjXWNk7KWPpbhxg.png" /></figure><p>Interestingly now if I do <strong>b.toString</strong> I have all these methods I can use on <strong>b </strong>even though we saw <strong>b </strong>is a primitive type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*vPB4mgmlOWknwc9iWaUi8A.png" /></figure><p>This is because in Javascript when we assign a variable <strong>(var b=5)</strong>, internally Javascript is going to <strong>Construct</strong> the number that we have added so that we have access to all these methods. And that&#39;s how we can use things like <strong>toString</strong>,<strong> toFixed</strong>. Even on string values or string primitives, we can have methods like these.</p><p>Javascript sees that you want to use Object methods, so it automatically assumes you meant the object instead of primitive so it runs the constructor object internally. This is how things like <strong>new Date()</strong> works as well.</p><p>You are creating objects and it&#39;s useful because they have a built-in prototype so that on this date we can run different sorts of methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*8CfTCJkHEjSoWrVCWF4EXw.png" /></figure><p>So yes technically in Javascript, everything is an object.</p><blockquote>So yes, technically in Javascript, everything is an object.</blockquote><p>Everything has a constructor function with the exception of<strong> null</strong> and <strong>undefined</strong>. We have constructor functions for everything so that we have methods that we can use on them.</p><h3>Ultimate OOP in Javascript.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hceq3FikqfuZJYP1Xdhksw.png" /><figcaption>constructor functions</figcaption></figure><p>Remember our constructor functions? No one really liked the prototype way of adding methods. So with ES6, Javascript finally introduced the <strong>class </strong>keyword.</p><blockquote>OOP was created with the <strong>class </strong>keyword idea in mind. A class is a blueprint of what we want to be created.</blockquote><p>OOP was created with the <strong>class </strong>keyword idea in mind. A class is a blueprint of what we want to be created.</p><p>Let’s see how this works.</p><p>We can simply define our Elf class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*O9A1rztwXUDUHggPt5-5cg.png" /></figure><p>Now as OOP suggests, we want to keep our functionality inside of this box — the <strong>class</strong>. Our properties, methods, the state, and all the actions together in a contained environment object.</p><p>Every time we instantiate we use the<strong> new</strong> keyword and the class.</p><p>This is the true beauty of OOP. We are modeling real-life scenarios. We are creating an Elf’s class which is a blueprint of what we want elves to be like.</p><p>Elves have names. They have weapons. They can also act on these properties like <strong>attack()</strong>. And you can just keep adding methods to the same location that holds the entire Elf object.</p><p>Anytime we need to update something or change or add a method, we can just change it here and all the instances of Elf will get that update.</p><p><strong>Instance </strong>is a common word that you will hear a lot when we use classes.</p><p>An instance happens when we call a class and create an object out of the class. For example, Peter is an instance of Elf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*WgeLvVYDbTMrsxdYjVTEew.png" /><figcaption>Peter is an instance of Elf</figcaption></figure><p><strong>Instanceof</strong>, therefore, is the language we can use to say that we are creating an instance of a class.</p><p>This with the <strong>new</strong> keyword is called <strong>Instantiation</strong>. We are instantiating a class.</p><p>If I remove the <strong>new </strong>keyword I get a very detailed error. <em>Class constructor cannot be invoked without new</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xx7qpI_O5atULaOFIDqXQ.png" /></figure><p>And there you have it. Here, we finally have OOP, or do we?</p><p>Not quite.</p><blockquote>This is what we call<a href="https://en.wikipedia.org/wiki/Syntactic_sugar#:~:text=In%20computer%20science%2C%20syntactic%20sugar,style%20that%20some%20may%20prefer."> syntactic sugar</a>. Underneath the hood, we are still using prototypal inheritance. We aren&#39;t using classes as classes work in other languages. This is the closest that Javascript is going to get to classes.</blockquote><p>This is what we call<a href="https://en.wikipedia.org/wiki/Syntactic_sugar#:~:text=In%20computer%20science%2C%20syntactic%20sugar,style%20that%20some%20may%20prefer."> syntactic sugar</a>. Underneath the hood, we are still using prototypal inheritance. We aren’t using classes as classes work in other languages. This is the closest that Javascript is going to get to classes.</p><p>Underneath the hood, they are still using the<strong> new</strong> keyword, with the <strong>prototype</strong>.</p><p>So why didn&#39;t we just create classes from the beginning? Wouldn&#39;t it make everything easier?</p><p>Because classes aren&#39;t necessarily the answer to everything. But also as the creator of the language said:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNoN2UiHsy7aJFt45VAElA.png" /><figcaption>source: zero to mastery</figcaption></figure><p>Brendan Eich was tasked with creating a language that would attract Java developers that were used to classes and OOP concepts. <br>But at the same time, they wanted to create a competing language. And for marketing purposes, they couldn&#39;t make it the exact same.</p><p>He had to be creative. He used prototypal inheritance which is different from how classes work in languages like Java and C++.</p><blockquote>In other languages, classes are an actual thing. In javascript, classes are still just Objects.</blockquote><p>In other languages, classes are an actual thing. In javascript, classes are still just Objects — Everything in Javascript is an object.</p><h4>Does Javascript have classes?</h4><p>Yes, they do as syntactic sugar. But the class keyword is just prototypal inheritance.</p><p>And some people call this <a href="http://theoryapp.com/javascript-inheritance-pseudoclassical-vs-prototypal/#:~:text=Pseudoclassical%20Inheritance,to%20build%20the%20inheritance%20chain.&amp;text=It%20also%20adds%20a%20method,is%20inherited%20in%20the%20instance.">pseudo-classical inheritance</a> because it&#39;s not real classical inheritance.</p><p>But looking at this, I hope you can see how we go from repetitive code, which was harder and harder to maintain to something a little bit more organized. We’ve created this grouping of functionality that is easier to maintain and extend.</p><p>By the way, you might be asking yourself, why don&#39;t we just add the attack() method to the constructor?<br>It’s because every time we use the <strong>new</strong> keyword and create or instantiate a class, the constructor function gets run simply because each elf has a unique name and perhaps a unique weapon.</p><p>But attack() is shared by all instances of the class</p><p>If we moved attack to the constructor, that&#39;s going to take up memory space.</p><p>Instead of creating an attack function from each object which is what we would do if we added to the constructor, and that&#39;s something we have tried to avoid. Instead, we just have one. One function in one location that all these instances can access.</p><h3>Object.create Vs classes</h3><p>There are people who love classes and people who never want to use them. Some people want to avoid using the<strong> new</strong> keyword and <strong>this</strong> because they say it causes too much confusion.</p><p>And so this is just personal preference. Highly respected programmers love classes. Other highly respected programmers hate classes. And there is no right or wrong.</p><p>But it&#39;s important to note that everything we have done with classes can be done with<strong> Object.create()</strong>.</p><p>With<strong> Object.create()</strong> we actually have everything that we need with none of the mess. We are able to create these prototype chains without pretending like we have classes</p><p>Some people call <strong>Object.create()</strong> pure prototypal inheritance as in that&#39;s the pure way of doing it instead of pretending like we are someone else.</p><p>What you use is up to you. Most of the Javascript community doesn&#39;t use <strong>Object.create()</strong> as much as the class syntax.</p><p>In most cases especially the newer codebases that use OOP principles, they will use <strong>class</strong> but the beauty with Javascript is that it’s multi-paradigm. It allows us to have a lot of options to code the way that we want based on the problem at hand and the team dynamic we have with other programmers.</p><h3>4 ways to manipulate the this keyword</h3><ol><li>The first one was this idea of <strong>new</strong> binding. This binding is used with constructor functions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpwnAcE8SzOrNnA2Hl56Ag.png" /></figure><p>The<strong> new</strong> binding allows us to assign <strong>this</strong> to the object that we instantiate. So <strong>person1</strong> would be the this keyword.</p><p>That&#39;s one way we can manipulate this keyword.</p><p>2. The other way is called <strong>implicit binding.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*La3h0RPWNLW7IclmOVv4Yw.png" /></figure><p>Here <strong>this </strong>will refer to <strong>person</strong>. That&#39;s implicit binding; it’s the most common one.</p><p>3. We also saw explicit binding. <br> It’s when we dictate exactly what the <strong>this</strong> keyword should refer to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgprSTidkKMRna5ZMlS2ng.png" /></figure><p>Initially, <strong>this </strong>is going to refer to<strong> person</strong> just like we saw above. Now if we want <strong>this</strong> to refer to the window Object we can explicitly tell it what to <strong>bind</strong> to. And we say bind to the window object.</p><p>Explicit binding uses <strong>call</strong>, <strong>bind,</strong> and <strong>apply </strong>to explicitly tell the program hey this is what I want <strong>this</strong> to be. I want it to be the window.</p><h4>4. this and arrow functions.</h4><p>With arrow functions, we learned that unlike all the other times where <strong>this</strong> is dynamically scoped — it gets determined whenever it gets called, with the arrow functions, we can do lexical scoping. That is wherever we write the function, that&#39;s where<strong> this</strong> binds to.</p><p>So that I can do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgWezbNffZIcSOroqQRHyg.png" /></figure><p>Here everything is working because we are using arrow functions. If we didn&#39;t use an arrow function and just used a regular function, in that case, <strong>this </strong>would be the window object which we usually never want.</p><p>This all allows us to harness the power of<strong> this</strong>.</p><h3>Inheritance</h3><p>A core of OOP is <strong>inheritance</strong> — passing knowledge down.</p><p>Remember at the start we decided to create this fairy tale game that had all these characters. And we started with Elves. But as you can see our goal is to have many things, not just Elves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*O9A1rztwXUDUHggPt5-5cg.png" /></figure><p>We want to have a <strong>dragon</strong>,<strong> knight</strong>, <strong>king</strong>, <strong>queen</strong>, and maybe some magicians.<br>So using this OOP principle of <strong>inheritance</strong>, how can we accomplish this with the work that we’ve already done?</p><p>Let&#39;s say that I wanted to have a new player, and this player is an Olga called Shrek. How would I go about creating this Olga?<br>Of course, the worst thing I could do is copy and paste this code to create an Olga class.</p><p>Copying and pasting code something that we want to avoid.</p><p>One option we have is to copy the elf and extend it. In order to copy what we already have, we can use the spread operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*p7MYGg9b7CrdrraFP-2KyA.png" /></figure><p>Here I have copied Peter into the Ogre variable.</p><p>But now if I do<strong> Orge__proto__ </strong>I get the base object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-m1iLw3HYjmUq88sxxXig.png" /></figure><p>And Peter?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1CFeuuXtVOw-taloxepdA.png" /></figure><p>I get the<strong> Elf</strong>.</p><p>So I have cloned the object but <strong>Ogre</strong> doesn&#39;t have <strong>Elf</strong> as the base class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*406vmIJos0rXln7DruwP_Q.png" /></figure><p>These objects are not referring the same place in memory. They are completely different things. But I have also lost the prototypal inheritance chain.</p><p>I can’t even do <strong>Orge.attack().</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dMe-qBAV-DhCyyspFzqmQ.png" /></figure><p>I don&#39;t have<strong> attack()</strong> — so that&#39;s a problem.</p><p>How can we extend this? <br>This is where inheritance comes in. It used to be really difficult to do with Javascript before we had this class syntax. It involved a lot of ugly prototype code.</p><p>We have changed the naming a little bit with our example. Our superclass is now <strong>Character. <br></strong>From this superclass, Elf <strong>extends</strong> — which is a keyword the <strong>Character</strong> class.</p><p>This something called <a href="https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/">subclassing</a> in OOP.</p><p>That is we have a base class or a superclass and a subclass. We want to inherit from the <strong>Character</strong> class all its properties and methods and create something new out of it extended with <strong>Elf</strong>.</p><p>Let&#39;s make this more interesting. Let&#39;s say that the Elves have an extra property — a<strong> type</strong> property to let us know what type of Elf they are.</p><p>How would we go about doing that? <br>Let’s add the type property. If I add a constructor and I do this.type = type, does this work?</p><p>We have to instantiate the Elf class and give it the name and weapon; also we want to have the type. So maybe we will have a third parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7mhGscbqkyp0lxP7qLAdCw.png" /><figcaption><strong>class Elf extends Character </strong>means set the prototype __proto__ to point to Character. Elf now has a prototype chain up to Character.</figcaption></figure><p><strong><em>Must call super…..</em></strong></p><p>What this is saying is that in order for us to have our constructor and be able to use <strong>this</strong>, and know what <strong>this</strong> is referring to, we need to call <strong>super </strong>which here is<strong> Elf</strong> and not the<strong> Character,</strong> we have the special keyword called <strong>super.</strong></p><p>And by doing<strong> super</strong> inside of the constructor, it says call the superclass of<strong> Elf </strong>which is <strong>Character. </strong>So it goes up and calls the <strong>Character</strong> so that we can create <strong>this.name</strong> and <strong>this.weapon</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twwSPu0KIAgcaIms13C01A.png" /><figcaption>Inside super, we have to pass it <strong>name</strong> and <strong>weapon</strong>.</figcaption></figure><p>Now, this is standard especially with class-based languages where <strong>super</strong> is referring to the superclass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOh0FwuVwPvtRRFRrvkDzQ.png" /></figure><p>Because in order to use this keyword inside of the constructor, when we extend something, we have to call super first.<br>So that if I move the <strong>console.log() </strong>under and I run, I have Elf that has <strong>name </strong>and<strong> weapon</strong> attached to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*j6NLdIATIL37xHf1QlEHnA.png" /></figure><p>This is because when super runs the constructor, we now have an instance of character with these properties and we can use this.type to add type to it.</p><p>So that by the very end of our construction process, we have all our properties set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*gJj86eIPSG2eZTSZK7yoeQ.png" /></figure><p>Remember this keyword simply says who I am I? Who is calling me? In this case, we use the <strong>new</strong> Keyword so that <strong>this</strong> is going to be set to Elf.</p><p>But we started this video with us wanting to create an <strong>Ogre. </strong>So let&#39;s create another class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxZZPrymw8mDyTgcjzjDtg.png" /></figure><p>And if I do<strong> makeForte()</strong> here and run this, I am able to use<strong> makeForte()</strong> method or function on Shrek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*7pHKRAE5QssTOAjhUcRGgA.png" /></figure><p>But If I go and make Dolby make forte, I will get an error.</p><p>We are able to keep our code nice and organized and extend our base character to create all these different characters in our game. We can reuse the code that we’ve written before, but also extend these classes to have their own unique things — properties like type or even methods like <strong>makeForte</strong>.</p><p>Creating<strong> makeForte()</strong> meant that we created our own method just for the <strong>Ogre</strong> class. But we did underneath the hood is we extended the prototype.</p><p>It’s the same as saying <strong>Ogre.prototype.makeForte()</strong>. Underneath the hood Javascript created this for us because we used the <strong>class</strong> keyword.</p><p>It looks a lot nicer than having to use <strong>prototype</strong> but also as we have seen before, it can get a little confusing. Beyond the fact that it looks a lot cleaner, things just make sense and we are using some OOP principles like <strong>classes</strong>, <strong>extend, </strong>and using subclasses.</p><p>We are also using the <strong>new</strong> keyword to create instances. Underneath the hood, we are using prototypal inheritance of Javascript to make these prototypal chains between our objects.</p><p>To test that everything is connected properly, let&#39;s do a few tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*5HkQy5siy1-5j8t6m-Djdg.png" /><figcaption>Ogre is a constructor function so we do Ogre.prototype which is the object that contains all properties and methods available.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMPOhKPeuCd2dewPsxPAIg.png" /><figcaption>character.prototype. isProtorypeOf(Ogre.prototype)</figcaption></figure><p>All this prototype stuff is confusing. There is a better way to check these connections using is <strong>instanceof.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*vOCdJjkUEYJFBQVEp_Ur-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*jpRaC8rJYMASN40NnNs98A.png" /></figure><p>We get true because Dolby extends all the way from Character.</p><blockquote><strong>Instance</strong> is when we use the<strong> new</strong> keyword from a <strong>class. </strong>We create an instance of a class. Instance is essentially creating a version of the class.</blockquote><p><strong>Instance</strong> is when we use the<strong> new</strong> keyword from a <strong>class. </strong>We create an instance of a class. Instance is essentially creating a version of the class.</p><p><strong>Inheritance </strong>— which is what we do with the keyword <strong>extends</strong>, is inheriting something from a higher class. <strong>Inheritance</strong> in Javascript doesn&#39;t actually copy our functionality. Instead, it simply links up the prototype chain so you are not creating copies and making things inefficient.</p><p>Instead, whenever it doesn&#39;t find something lets say in the Ogre class, it&#39;s going to look up the Ogre superclass which is character.</p><p>So it&#39;s creating this efficient linking in Javascript using prototypal inheritance. And, unlike other class-based languages, Javascript is just object s— its objects inheriting from objects. There are no technical classes. Languages like Java on the other hand have actual classes. They are a thing.</p><p>And classes inherit from classes. The interesting thing is languages like Java and C++ actually copy objects when we do something like <strong>extend</strong>. Instead of what we do with Javascript which is we link and the objects are referenced. There is actually a bit of efficiency there in terms of memory.</p><h3>Public vs Private</h3><p>In many OOP languages that have classes, the idea of private and public fields is really important. In Javascript, we don&#39;t have that.</p><p>For anything that shouldn&#39;t be accessed, from a class or even an object, we would add an underscore to let other people know that hey this is private. You shouldn’t call it. But underscore doesn&#39;t really do anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*6r3vb1G31Pbm12mnxsaVkA.png" /></figure><p>I can still use this method and maybe even by mistake reassign it to just false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*8sJ6ans80X-2JVgb9dH8Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*TGSX9fBhYooNY98iLRgSxw.png" /></figure><p>So that now I have just overwritten everything.</p><p>Other languages like Java have things like <strong>private</strong> — a keyword that makes things private and may only be used inside of the class.</p><p>But there is an <a href="https://github.com/tc39/proposal-private-methods">Ecma script proposal </a>coming up to solve this issue.</p><p>The Ecma script proposal is in stage three and its for class field declarations and perhaps a few more changes.</p><p>For now, the closest to doing or having <strong>private</strong> state or private data, that can only be accessed inside of the class is something we are working towards.</p><h3>OOP in react.js</h3><p>By now you can spot OOP in the wild.</p><p>For example, if you ever used react.js, you can see how they use OOP principles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*w5pQsjjxANh3WfpDRA5Caw.png" /><figcaption>source: <a href="https://reactjs.org/">https://reactjs.org/</a></figcaption></figure><p>We can now look at the code and understand it better. We have a<strong> timer</strong> class that we create that extends<strong> React.component. React.component </strong>is something that comes from the react team. They’ve built this class that has all these features for us so that we can use things like <strong>render() </strong>that comes automatically for us.</p><p>We are using someone else’s code and we are extending the base component there to add our own features. We have constructors that receive props. We have <strong>state</strong> — the state of our toggle class, and then we create our own methods on this class such as <strong>tick()</strong>.</p><h3>The pillars of OOP</h3><p>We started with an idea of building a game. Using this idea we started learning about OOP and how we can use this programming paradigm to better our code and make it more organized. Inadvertently, we just learned the four pillars of OOP.</p><ol><li><strong>Encapsulation</strong>: Remember that before OOP we had procedural programming. Unlike procedural programming where we have functions modifying data with no real structure, OOP puts Objects in a container and organizes things into units that model real-world applications.</li></ol><p>This is <strong>Encapsulation</strong>. We wrap code into boxes that are related to each other so that these boxes can interact with each other using methods and properties that we make available. This makes code easier to maintain and more reusable. Here we have all these nice class packages that we can just use whenever we want.</p><p>2. <strong>Abstraction: </strong>This just means hiding the complexity from the user. That is creating simpler interfaces such as taking care of the class and that&#39;s left to do is to instantiate the class. Such as an instance of an<strong> Elf</strong> with all the properties and methods already there for you.</p><p>And the idea of abstraction says here are the properties and methods that you can use don&#39;t worry about anything else. I will do all the calculations behind the scenes. This reduces complexity because we can just see the methods and understand what a <strong>class</strong> can do. Abstraction also helps when we have private methods and private variables — something that Javascript is working towards.</p><p>3. <strong>Inheritance</strong>: By inheriting from other objects we avoid rewriting the same code and we also save memory space by having shared methods.</p><p>Inheritance is a very powerful concept and its definitely my favorite part of OOP.</p><p>4. <strong>Polymorphism.</strong> The word itself means many forms. <strong>polymorphism</strong> is heavily debated. There are many interpretations of what it means. But the idea is to call the same methods on different objects and each object responds in a different way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*iYxII1kBFZfdIVd5zuJhow.png" /></figure><p>Here let’s say that the <strong>Elf </strong>and <strong>Ogre</strong> class have a different way of attacking. For example, the Elf attacks with a <strong>cry</strong>, and the<strong> Ogre</strong> just returns <strong>arrrghhhh.</strong></p><p>Now running <strong>Dolby.attack(wee)</strong> and <strong>Shrek.attack() </strong>gives us <strong>weeeeeee </strong>and <strong>arrrghhhh.</strong></p><p>This is a very basic way of what polymorphism is but the idea of the ability to appear in many forms is there. We are simply overriding the <strong>attack()</strong> method where the same method acts differently for each type of class. Or we can do method overloading which is adding extra features or extra parameters to add on to what that method can do.</p><p>The idea with polymorphism in OOP is that it has the ability to process objects differently depending on their data type or class. Now because Javascript is a dynamically typed language, it limits the amount of polymorphism that we can have but the idea is still the same.</p><p>The ability to redefine methods for derived classes and allowing us to reuse some of the functionality but also customize methods to their own objects and classes. Polymorphism is useful because we don&#39;t have to necessarily copy and paste code over and over. We can use some of the functionality from the superclass to adapt to our own specific needs.</p><h4>And these are the four pillars of OOP.</h4><p>And we have been using them all along. With the help of these pillars, we accomplished the goal that we set out to do at the beginning of this section.</p><p>We created code that is clear and understandable.</p><p>Code that is easy to extend.</p><p>Easy to maintain because we don&#39;t have to worry about those prototype chains. We just used simple classes. Everything inherits from a superclass. And if we have to make a modification on a class we can just modify it in one location.</p><p>We also learned how memory efficient it is especially in Javascript where objects use references instead of cloning and copying each other.</p><p>And then finally, we are able to make our code DRY. We don&#39;t keep repeating ourselves over and over for each object. Instead, we have one place where we could create functionality.</p><p>So now we have a way to think about code in a critical and intelligent way; to structure your code. Instead of writing code one by one, line by line, you now have a baseline to start thinking about code and how you should organize it. How should different things speak to one another in order to create these programs that have these ideas in mind?</p><p>Exercise on polymorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*gSjphUjlbVxxcWUoQuW37A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*c-batC6BQkbnD1zQ1tLk_g.png" /></figure><h3>And there you have it with OOP.</h3><p>So what did we learn?<br>1. The <strong>this </strong>keyword<br>2. The<strong> new</strong> keyword<br>3. All about prototype <br>4. ES6 classes<br>5. Class-based languages like Javas and C++<br>6. Inheritance<br>7. Object.create<br>8. Private vs Public<br>9. 4 principles of OOP</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d6423dde9a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-comprehensive-look-at-object-oriented-programming-oop-91d6423dde9a">A comprehensive look at Object-Oriented Programming(OOP)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about Prototypal Inheritance — The second pillar of Javascript]]></title>
            <link>https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d851cd4509</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[myjavascriptjourney]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Tue, 26 May 2020 02:46:12 GMT</pubDate>
            <atom:updated>2020-07-04T02:15:03.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>All you need to know about Prototypal Inheritance — The second pillar of Javascript</h3><h4>Javascript pillars</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p23OawDcvNRueAw-Mgpg4w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@_miltiadis_?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Miltiadis Fragkidis</a> on <a href="https://unsplash.com/s/photos/chain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article is inspired by Andrei’s course <a href="https://www.udemy.com/course/advanced-javascript-concepts/">https://www.udemy.com/course/advanced-javascript-concepts/</a></p><p>What we will learn here will help us understand Object-oriented programming(OOP).</p><p>In case you haven’t seen the first pillar&gt;&gt;&gt;</p><p><a href="https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c">All you need to know about Closures — The first pillar of Javascript.</a></p><p>Remember arrays and functions are just objects in Javascript.</p><p><a href="https://medium.com/@allansendagi/javascript-foundation-function-invocation-arguments-keyword-variable-environment-scope-chain-97d4888cf319">Javascript Foundation — Function Invocation, Arguments keyword, Variable environment, Scope chain.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*OoSiQcFcMJGbEA2iIetlAA.png" /><figcaption>Source: <a href="https://zerotomastery.io/">Zero to Mastery</a></figcaption></figure><p>It is because Javascript uses something called prototypal inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*MR6W6dgP1OJCk-IVyVlH9Q.png" /><figcaption>Functions and Arrays are objects. The chains are prototypal inheritance</figcaption></figure><p>Inheritance is an object getting access to the properties and methods of another object.</p><p>From our diagram above, the array object gets access to the methods and properties of the object in Javascript — same with the function through this chain that we call prototypal inheritance.</p><blockquote>Inheritance is an object getting access to the properties and methods of another object.</blockquote><h3><strong>Let&#39;s look at arrays as an example:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ese6eKYm9OUbpXi0ekcrw.png" /></figure><p>By doing <strong>__proto__</strong> we see that we get all the methods that arrays have. What happened is that I created a new array and our new array was created from what we call the Array constructor. This big array constructor created our array variable that contained an empty array. We did <strong>__proto__</strong> to go up the prototype chain and get into the big array.</p><p>By that theory, if I go up the prototype chain once more, I should get an object.</p><blockquote>By that theory, if I go up the prototype chain once more, I should get an object.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCtyO1HymTWSWcE2DrzYDg.png" /><figcaption>The base object in Javascript</figcaption></figure><p>This is the object that everything in Javascript gets created from including functions and arrays.</p><p>We see that we have some properties on this object. For example <strong>toString </strong>method.</p><figure><img alt="The base object where everything in javascript comes from" src="https://cdn-images-1.medium.com/max/1024/1*1UuCshlSPPEoQeL2IAlPVg.png" /></figure><p>That means that everything that is a descendant of this object will get the <strong>toString</strong> method which means that even our array has a <strong>toString</strong> method because of this prototype chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*SFQMYNGdDhP96z2fNnxUOA.png" /></figure><p>As we said, an object gets access to the properties and methods of another object through the prototype chain.</p><h3>Now let&#39;s look at functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*I7fwgUeAJ2QB4yJGm_FlAA.png" /><figcaption>An empty function</figcaption></figure><p>If we go up the prototype chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*oNraniqY3eIJUt3-ULuUOw.png" /></figure><p>We get the native function. This is our base function where all functions are created. So that when I go up the prototype chain again, I get that base object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVeMRADkcOJ1EDhAiW5ZFQ.png" /></figure><h3><strong>And objects?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8xPTaHyncesE_SRuB32_g.png" /></figure><p><strong>__proto__</strong> gets us to the base object. Here I created my <strong>obj</strong> variable from that base object.<strong> obj </strong>has the prototypal chain to the base object</p><p>And this is what prototypal inheritance is.</p><p>This feature is quite unique from other languages such as C# or Java. They use something called Classical inheritance.</p><blockquote>This feature is quite unique from other languages such as C# or Java. They use something called Classical inheritance. Javascript uses prototypal inheritance.</blockquote><p>Javascript uses prototypal inheritance. And although in Javascript we do have the<strong> class</strong> keyword, this is what we call<a href="https://en.wikipedia.org/wiki/Syntactic_sugar"> syntactic sugar</a>. There are no classes in Javascript. We only have the prototypal inheritance.</p><h3>The prototype chain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*HDanJ9vTFZGKSnVk6jckwQ.png" /><figcaption>Source: <a href="https://zerotomastery.io/">Zero to Mastery</a></figcaption></figure><p>If I run this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*m3C6PE9QNNrCxf5X8h0TXg.png" /></figure><p>Let&#39;s have another object. A weaker <strong>lizard</strong> without a lot of power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*PC3KeomIfVvJz9SEF_xLUQ.png" /></figure><p>Now suppose we wanted to borrow a method from the dragon object. How can we do that?</p><p>Previously, we have used <strong>bind()</strong> to borrow methods from an object.</p><p><a href="https://medium.com/@allansendagi/javascript-fundamentals-bind-and-currying-c851902c40ae">Javascript Fundamentals: bind() and currying</a></p><p>With<strong> bind()</strong> we can do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*EmG86_lndr8jj8sL6A_IIQ.png" /><figcaption>Borrowing sing from the dragon.</figcaption></figure><p>So that when we run our code we see that we have a borrowed method from the dragon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*xGO1TowmdWeD9FyZk77jHA.png" /></figure><p>But let&#39;s say this object gets a little more complicated. Maybe for us to be able to <em>breathe fire</em>, we have to have the <em>fire</em> property set to true.</p><p>So that we can have a conditional statement before we can have our battle cry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ttduUBtkvG95Zvf9v1GsQQ.png" /></figure><p>Unfortunately now our lizard doesn&#39;t have <strong>fire</strong> set to true. So our <strong>singLizard</strong> returns undefined even though we borrowed the method. We don&#39;t have the <strong>fire</strong> ability, so it&#39;s never going to sing <strong>I am kiki the breather of fire.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Qpv5fRQfEfYQRiSzt8weA.png" /><figcaption>lizard can’t sing even though we borrowed the method.</figcaption></figure><p>Now, of course, we could simply manually add the property, but you can see how that could get very complicated. Because what if we had a big object and we wanna borrow more than just one method? Maybe inherit a bunch of the <strong>dragon</strong> properties for the <strong>lizard</strong> as well?</p><p>This is where we use prototypal inheritance.</p><p>We could have a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">prototype chain</a> that says hey, I want <strong>lizard</strong> to inherit all these properties and methods from<strong> dragon</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*YTwRhq0qft23dp1Vtsb4Yg.png" /></figure><p>We can see that we have managed through our prototype chain to inherit the properties and methods from <strong>dragon</strong> except for the methods and properties that we have —<strong> name</strong> and <strong>fight</strong>; these stay the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xj2ZRPY-ACA7f9zTgfqCSw.png" /><figcaption>calling something dragon doesn&#39;t have throws an error</figcaption></figure><p>And if we call something that <strong>dragon</strong> doesn&#39;t have? We get an error because we go up the prototype chain and find that <strong>dragon</strong> has no<em> dance</em>.</p><p>From there we go up the prototype chain of <strong>dragon</strong> again which is the original base object and there also there is no dance.</p><p>Note that this also means that I can use whatever methods that the base object has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNU6mgAFMiBWTkI2LebOCw.png" /><figcaption>dragon can use properties and methods from the base object</figcaption></figure><p>If for example, I use<strong> isPrototypeOf</strong> method on dragon which comes with the base object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btOs-j-5GmI9TYx5zq24-A.png" /><figcaption>isPrototypeOf method</figcaption></figure><p>It works because we see that dragon is a prototype of <strong>lizard</strong>.</p><p>Our Javascript engine goes up the chain to the base object to use the functionality of<strong> isPrototypeOf</strong>.</p><p>Let&#39;s have our example again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*a8m8eqRxR6VsTkvF5P3xEg.png" /></figure><p>If I run this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EegjU6FgLd_jQfkbolN4jg.png" /><figcaption><strong>lizard</strong> has these properties because we have created a prototype chain to<strong> dragon.</strong></figcaption></figure><p>But as we mentioned earlier we can also use methods from the base object, for example, <strong>hasOwnProperty</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*rH27oLVjRoKwpygZ98iQ9Q.png" /></figure><p>What we are saying here with <strong>hasOwnProperty</strong> is that only log what lizard has as its own property. Therefore, we only get <strong>name</strong> and <strong>fight </strong>— the other properties are inherited from up the prototype chain.</p><p>You can see that we are not copying these methods. Instead, Javascript automatically looks through the prototype chain to find these methods.</p><blockquote>But you’re probably asking yourself why you haven’t seen this <strong>__proto__ </strong>before in code bases yet it seems pretty useful. Why isn’t it everywhere?</blockquote><p>But you’re probably asking yourself why you haven&#39;t seen this <strong>__proto__ </strong>before in code bases yet it seems pretty useful. Why isn’t it everywhere?</p><p>Now although we have use this <strong>__proto__</strong> to demonstrate here, you shouldn&#39;t really use it. It&#39;s bad for performance and there is a different way to inherit properties.</p><p>We never want to manually assign when we create the prototype chain and create that chain ourselves. It&#39;s going to mess up our Javascript compiler pretty badly.</p><p>We can properly do it with <strong>Object-Oriented Programming</strong>.</p><h3>Why prototypal inheritance is useful</h3><p>The fact that objects can share prototypes means that you can have objects that are pointed to the same place in memory thus being more efficient with our code.</p><p>Imagine if we had a lot of <strong>lizards</strong> and we just copied all this functionality of the <strong>dragon</strong> onto the <strong>lizard</strong> to a different place in memory. That can get overwhelming fairly soon. With prototypal inheritance, instead of copying all this to a different place in memory, we just have one reference.</p><blockquote>With prototypal inheritance, instead of copying all this to a different place in memory, we just have one reference.</blockquote><p>Anything that inherits from <strong>dragon </strong>will just use this one instance because the Javascript engine is just going to look up the prototype chain.</p><p>As a side note, whenever we get <strong>undefined</strong> on something for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*AlFYxg_6HelnyHZoP921Cw.png" /></figure><p>Whenever the Javascript engine doesn&#39;t find anything up the prototype chain, we get these errors or undefined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5wMRFpzzxxBMJJcCYH6ZQ.png" /></figure><p>We see that if we go higher up passed this base object, we get <strong>null </strong>— <strong>Null</strong> meaning there is nothing there. When Javascript was created, Undefined was used for <strong>we don&#39;t have that variable.</strong></p><p><strong>Null</strong> meant there is absolutely nothing there.</p><p>Because of its prototypal inheritance nature, we needed a way to say, hey past the base object there is nothing there. That&#39;s why we have <strong>null</strong>.</p><h3>Let&#39;s dig a little deeper.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*LgknvIRlaF4YBdg2gV_cgA.png" /><figcaption>obj hasOwnProperty name.</figcaption></figure><p>But if I do <strong>obj.hasOwnProperty</strong>,<strong> </strong>I get an error because <strong>ob</strong>j doesn’t have this method itself. It has this as a property up the prototype chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*pGyUkKjqionlOcap7E9cog.png" /></figure><p>How about a function?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*_QJA-nt219ysn-1fjHcxkg.png" /><figcaption>a hasOwnProperty is true unlike call, bind or apply</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*BXFkEH0Atxtn-1wkbolbMA.png" /><figcaption>all functions have call, bind and apply but none of them is true here</figcaption></figure><p>This is because a function is a special type of object. It&#39;s a callable object where we have code that can be invoked, we have an optional <strong>name</strong> field and we also have <strong>properties </strong>we can add to the function — this is all because its an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*MAPzxeza7B_4O7kyE4Uk8g.png" /><figcaption>A function has call(), apply() and bind() as properties.</figcaption></figure><p>But these properties aren&#39;t on the <strong>multiplyBy5 function</strong>. Instead, this is up the prototype chain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*8NaoIJ1yIDRlXsVP9lb6Ng.png" /><figcaption>diagram a:1. Source: Zero to Mastery</figcaption></figure><p>With <strong>multiplyBy5</strong> if I go up the prototype chain, I will have the native function that all functions get created from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*4m9bHOloAWF9DnTtS8Xvfg.png" /></figure><p>Now if we can capture this base function and store it, we see that all these properties come with this native function including apply(), bind() and call().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*I-5zEAwVo-imyt8PpQ523w.png" /></figure><p>This is what&#39;s happening in diagram a:1:<br><strong>multiply by 5 </strong>has a <strong>__proto__</strong> property that links up to the native function that has <strong>call()</strong>, <strong>apply()</strong> and <strong>bind()</strong>.</p><p>As you can see there is a pattern here: <strong>__proto__</strong> links to <strong>prototype</strong>.</p><p><strong>MultiplyBy5</strong> — a callable object that is invokable, with name, properties(call, bind and apply) also has<strong> __proto__</strong> that links to the native function which also has a <strong>prototype</strong> property. The prototype property is where call(), bind() and apply() live.</p><p>Let’s try this out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARC76fFBy6EUVG7pV8WBfw.png" /><figcaption>__proto__ points to Function.prototype — the native function. We can see its the same function multiplyBy5 points to.</figcaption></figure><blockquote><strong>__proto__</strong> is simply a reference or a pointer to the object prototype up the chain.</blockquote><p><strong>__proto__</strong> is simply a reference or a pointer to the object prototype up the chain.</p><h4>Let&#39;s test this out further with an array.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*8pkYCsvBp7WRWQG2xzn10w.png" /><figcaption>We are being efficient with our memory so the map function lives up the prototype chain.</figcaption></figure><p>Map property lives up the prototype chain with the base Array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*JOUCR0U51GLGn_B-80Atsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqTVTrSAhr9TbbgS3icf0w.png" /><figcaption>array.__proto__ is pointing to the naive array Array.prototype.</figcaption></figure><p><strong>[].__proto__</strong> is pointing to the father <strong>Array.prototype</strong></p><p>To review,</p><p>Arrays and functions are objects in Javascript. <strong>multiplyBy5</strong> is a special type of object that is a callable object. However it doesn’t have call, apply or bind as its own properties, it uses prototypal inheritance to inherit from the base function.</p><p>The key here is<strong> __proto__ </strong>points to the prototype up the chain and the <strong>__proto__ </strong>property actually lives on the prototype. This way we are able to be efficient with our memory, we are able to use the <strong>map</strong> function or <strong>for each. </strong>We just write them once instead of copying them each time.</p><h3>How to create our own prototypes</h3><p>We agreed that <strong>__proto__</strong> isn’t something that we should use for performance reasons in our Javascript code.</p><p>There are many safe ways to do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*H6wlw9ECQHus0f8X9zLvVw.png" /><figcaption>Socrates inherits from human with Object.create</figcaption></figure><p><strong>Object.create</strong> is one of the ways we can use to inherit from an object in this case human</p><p>So that if we do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*p-uNtS-tz1vItB1YRnTKsQ.png" /><figcaption>We’ve inherited from human</figcaption></figure><h3>Only functions have the prototype property</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*5xzldeAWrsGjP7ivQmrSiw.png" /></figure><p>However, when we create a function like this, this prototype we don&#39;t really use. It just gets created but we never really make use of it. Now although <strong>prototype</strong> is a property on all functions, the only time that we really use it is when we create a constructor function.</p><p>Constructor functions usually start with a capital letter <strong>F </strong>and they contain the actual prototype or blueprint that we use.</p><p>For example, if I do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*a5Hclrgps0JLWOlfksJoYA.png" /></figure><p>Now we know that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*eFcmQJe72p-5dBsXnP_ubg.png" /></figure><p>Equals the same thing.</p><p>Now if we go up the chain again, we get our base object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmag40S_8B_s06j5RkJe0g.png" /></figure><blockquote>But we have just said that prototypes only exist on functions?</blockquote><p>If I do Object.prototype, we get the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJrlOsYY3rKVVcH1D7fX9Q.png" /></figure><p>But haven’t we just said that the prototype property only exists on functions?<br>This is where things get a little confusing.</p><p>Because with this base object, if we do <strong>typeOf </strong>Object, we see that it’s a function!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*aeIM6nMaISYJNApCfuYc1w.png" /></figure><p>Well, this is because it has the prototype property.</p><p>Remember the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects">standard built-in objects </a>in Javascript where we have all these things like Fundamental objects like Object, Function, Boolean, Number, and Dates, Strings — all with capital letters. If we open up the Object, we see that this object is the Object constructor that creates the object wrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*F4f0iQyiPjDiiq2cWQiOZg.png" /></figure><p>Remember that for us to perform an action in a program, we have to have a function — that&#39;s what a program does. It stores data, and we use functions to manipulate that data. So when we do something like <strong>const obj = {}</strong>, underneath the hood, Javascript has to create that object, and in order to create <strong>obj</strong>, it uses the object constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*fkkSf4J804fpvUw3wlnivA.png" /></figure><p>Because this is now an actual object that we’ve created from the object constructor.</p><blockquote>The takeaway?<br>Every function has a prototype property. And it references to an object used to attach properties that will be inherited by objects further down the prototype chain. The last object in a chain is the built-in <strong>object.prototype.</strong></blockquote><p>The takeaway?<br>Every function has a prototype property. And it references to an object used to attach properties that will be inherited by objects further down the prototype chain. The last object in a chain is the built-in <strong>object.prototype</strong>.</p><p>Remember the difference: Object is a function because it has the prototype. The <strong>Object.prototype</strong> is what we call the base object — that is the very last object that we can look for properties on before we point to <strong>null</strong>.</p><p>As a side note:<br>If I created an empty object, I wouldn&#39;t be able to access <strong>obj.prototype</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*tKhQKijBridaow_VFtgtTg.png" /></figure><p>It&#39;s undefined. It&#39;s not a function.</p><p>What about <strong>array.prototype</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*bxPOlA98KMgLqFZG1pKSWA.png" /></figure><p>Its also not a function.</p><p>And “string”.prototype?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*IZp30xwBLEmPhaV9RNEVvQ.png" /></figure><p>It&#39;s also not available. We don&#39;t have prototype because well that&#39;s just a primary type.</p><h4>Only functions have a prototype.</h4><p>But from our standard built-in objects, if I do <strong>String.prototype</strong>, we have that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZZNZvGSpZOyMvgYndiQlw.png" /><figcaption>The string constructor</figcaption></figure><p>And strings have all these methods from the String constructor that they can inherit from.</p><h4>To summarise:</h4><p>Everything in Javascript is an object. And arrays and functions in Javascript are objects. They inherit through the prototype chain from the base object.</p><p>You can go up the prototype chain looking for properties on the prototype property. The prototype property also has <strong>__proto__ </strong>inside of it that links higher up to the next prototype chain.<strong> __Proto__</strong> always points to prototype.</p><p>And only functions have the prototype property. <br>At the end of the day, this was useful for us because using prototypes we avoid repeating ourselves. We avoid adding the same code over and over and being inefficient with our memory. But we can also start creating some interesting programing paradigms and practices using what we learned both prototypes and closures to write some really powerful programs.</p><h4>Let&#39;s finish off with exercises.</h4><p>Extend the functionality of the built-in Object.<br>1. Make the Date Object have a new method <strong>.last year() </strong>which shows you last year in <strong>YYYY</strong> format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*rypMa51w5gdz9uzlNDC-NQ.png" /></figure><p><strong>Solution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*IBFwUBm7BSy3VLkqyizwmg.png" /></figure><p>2. Modify .map() to print ‘ 🗺’ at the end of each item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*TMlI4f5m3C4rFm61WO5uWg.png" /></figure><p>2. How would you be able to create your own .bind() method using call or apply?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdYGakyur6dn6x8rTrk_Vw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d851cd4509" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/all-you-need-to-know-about-prototypal-inheritance-the-second-pillar-of-javascript-d8d851cd4509">All you need to know about Prototypal Inheritance — The second pillar of Javascript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I was laid off. Here’s how I picked up a new skill and what that taught me about today’s world.]]></title>
            <link>https://medium.com/@allansendagi/i-was-laid-off-heres-how-i-picked-up-a-new-skill-and-what-that-taught-me-about-today-s-world-9956ea05719f?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/9956ea05719f</guid>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[work]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Fri, 15 May 2020 13:35:41 GMT</pubDate>
            <atom:updated>2020-05-15T13:35:41.944Z</atom:updated>
            <content:encoded><![CDATA[<h4>A lot of times I felt like giving up the whole damn thing!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xhvp557ttWFVQDw4A7jpNw.jpeg" /><figcaption>Photo by Benjamin Davies on Unsplash</figcaption></figure><p>One year ago I was summoned by my former employer. The meeting was short. They just wanted me to know that business was bad and regrettably they had to let some people go. I was shook. But not for long.</p><p>A big part of me was happy the ordeal was over. But now what? I just didn’t want to do the next thing that came my way. So I resolved to acquire a new skill. I chose Coding. Why?</p><ol><li>Because I found coding the most affordable way to build something from scratch. I could finally build that application I always had in mind.</li><li>Because Technology is well-positioned to solve many complexities the World is facing.</li><li>I thought hey if I could just get good at this, maybe companies would even pay me to write software. So for the next 7 months, 3 hours daily I resolved to learn to code.</li></ol><p>I wish I could tell you it’s been an easy journey; it hasn’t. And clearly — even after a year I still have a lot to learn.</p><p>A lot of times I felt like giving up the whole damn thing.</p><p>There were times I thought that perhaps my brain isn’t wired for this stuff.</p><p>But I had read Mindset — Psychologist Carol S Dweck’s book which shows how embracing a growth mindset can help with learning.</p><p>I had also read Charles Duhiggs the power of habit and picked up a few lessons on the science behind why we do what we do.</p><p>And I picked up Cal Newport’s So good they can’t ignore you which stresses focusing on getting better. So I kept going, and every day I got a little smarter.</p><blockquote><em>I learnt how the internet works. I learnt how computers run programmes.</em></blockquote><p>I learned Javascript and the react library.</p><p>I acquainted myself with functional programming and object-oriented programming. I pored over data structures and Algorithms; I learned about servers and databases.</p><p>I documented my journey on <a href="https://medium.com/@allansendagi">medium</a>, I felt a little confident and so I began writing to business owners telling them about what I was learning and offered my help. I did a few interviews and now I work remotely with a team-building an independent search engine.</p><p>Now all this stuff left me really curious about today’s world. You see I am Ugandan but I call Dubai home. I used the internet to learn to code. I work with strangers who live in different time zones. I have leveraged research from top universities that I have never attended; most of them publish their work freely online.</p><p>So what has changed? Is it Ease of travel? Mindset shifts? Ease of access to capital? E-learning? The internet? Migration patterns? More people? More computers? More countries?</p><blockquote>The world is undergoing a historical transformation and nothing has remained unchanged</blockquote><p>I went digging to see what has changed. And yes, it’s all the above and a lot more. The world is undergoing a historical transformation and nothing has remained unchanged. Over the last 35 years, the barriers to acquiring mastery have become less forbidding. But we are either too busy at our jobs to notice or we simply ignore it all.</p><p>Because if barriers to entry are porous, why are billions of people still left out of the current economic system? Is it because the system is designed to offer no way out for a common man? or is it because our mental barriers are so strong that we are unable to see things any different.</p><blockquote>Can a girl from rural Uganda today overcome the barriers that killed her mother’s dreams?</blockquote><p>Can a girl from rural Uganda today overcome the barriers that killed her mother’s dreams? Can she find a way to leverage these new power shifts to get involved, acquire means of production, better her people, and maybe even shape the future of humanity? Is 16-year-old Greta Thunberg’s story unique?</p><p>Can a 40-year-old factory worker in the US who lives with the fear of being replaced by a machine find a way to reinvent himself?</p><p>The answer is Yes; both these people can. However, someone needs to show the girl that her odds have improved before time runs out; and a factory worker can only reinvent himself if he has been paying attention to the forces reshaping our world.</p><blockquote>It is, for this reason, I started involveall; a call for more people to get involved in shaping the direction of the world.</blockquote><blockquote>But the decks are stacked against the latter because the opening is small and it’s closing fast; future technologies are poised to further the divide between the haves and have nots.</blockquote><p>These transformations can be leveraged by those seeking to cement their grip on power as well as those who want to make their world a little better. But the decks are stacked against the latter because the opening is small and it’s closing fast; future technologies are poised to further the divide between the haves and have nots.</p><p>Because like Yuval Harari writes, this time those who will miss this train of progress won’t get a second chance.</p><p>I publish videos weekly. I think a lot more people should get involved in shaping the direction of the world because of the transformations and the stakes if we stay on the sidelines.</p><p><a href="https://www.linkedin.com/in/allansendagi/">https://www.linkedin.com/in/allansendagi/</a></p><p><a href="https://www.facebook.com/involveall.org/?modal=admin_todo_tour">https://www.facebook.com/involveall.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9956ea05719f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about Closures — The first pillar of Javascript.]]></title>
            <link>https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e7ed96f241c</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[myjavascriptjourney]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Fri, 15 May 2020 04:02:24 GMT</pubDate>
            <atom:updated>2020-07-04T01:52:27.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>All you need to know about Closures — The first pillar of Javascript.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiRHh3jPcyXCiFJMlQ7YRQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cristina_gottardi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Cristina Gottardi</a> on <a href="https://unsplash.com/s/photos/closures?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article is inspired by my Andrei’s course <a href="https://www.udemy.com/course/advanced-javascript-concepts/">https://www.udemy.com/course/advanced-javascript-concepts/</a></p><p>Closures and prototypes are the two pillars of Javascript which when understood properly gives you superpowers.</p><p>Closures in Javascript are possible because of two things:</p><ol><li>Functions are first-class citizens. We can pass functions around like data — like any other type in Javascript.</li><li>Lexical scope: Based on where our code is written, the Javascript engine knows before we even run the code what variables each function has access to.</li></ol><p>And that&#39;s what closures are — a combination of a function and the lexical environment from which it was declared.</p><blockquote>Closures allow a function to access variables from an enclosing scope or environment even after it leaves the scope in which it was declared.</blockquote><p>Closures allow a function to access variables from an enclosing scope or environment even after it leaves the scope in which it was declared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*6cdYniVmwnrXgGgRk1cbWg.png" /></figure><p><strong>function a </strong>and <strong>function b</strong> are higher-order functions because they return functions. <strong>function c</strong> is a normal function because we are just returning a piece of string. Let&#39;s run this code and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*yxaucxrTHKW_ptJMYerDOw.png" /><figcaption>function a returns function b</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*ArUqivgejjN--dqW_X_Z1A.png" /><figcaption>function b returns function c</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*qSDTf0iltoHQU3VUj_6FUQ.png" /><figcaption>function c gives us grandpa, father, and son.</figcaption></figure><p>The question then becomes: How did<strong> function c </strong>remember what grandpa was? Because if we remember how the Javascript engine runs code —</p><p><a href="https://medium.com/@allansendagi/javascript-fundamentals-call-stack-and-memory-heap-401eb8713204">Javascript Fundamentals — Call Stack and Memory Heap</a></p><p>we know that<strong> function a</strong> got run and then popped off the stack. And when things get popped off the stack, we remove the variable environment and things are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">garbage collected.</a></p><p>But here that is not the case; somehow<strong> son </strong>has access to <strong>grandpa </strong>and<strong> father </strong>even after we called <strong>function b</strong>!</p><p>So what just happened here? Well, closures happened.</p><p>With closures, when a function runs, it gets pushed onto the stack; we create a variable environment and the context execution has <strong>grandpa</strong> as a variable. It would also have parameters such as the <a href="https://medium.com/@allansendagi/javascript-foundation-function-invocation-arguments-keyword-variable-environment-scope-chain-97d4888cf319">arguments keyword</a> but because we haven&#39;t given it any other parameters, there are no other variables.</p><p>Once we call<strong> a()</strong>, it gets removed from the stack. It&#39;s gone but <strong>grandpa</strong> still remains. That&#39;s because grandpa goes into the closure box.</p><p>This closure box is technically where the memory heap is — it’s a bunch of memory and as soon as we don&#39;t need things anymore, it gets removed.</p><p>However, when the garbage collector comes, sees <strong>grandp</strong>a, it says there is closure here, it’s in the special closure box. This closure box I can’t clean up because there is something that is referencing <strong>grandpa</strong> from inside of it.</p><p>So the next <strong>b function</strong> gets called, again we add it to the stack. A new variable environment is created and we have <strong>father</strong> as our variable. Once we remove <strong>father</strong>, or once <strong>b</strong> gets popped off the stack, once again<strong> father</strong> is being referenced by another function inside of it so it gets put into the closure box.</p><p>And then <strong>c</strong> comes around, gets called and we have <strong>c</strong> in the variable environment. When we return the statement, <strong>grandfather</strong>, <strong>father</strong>, <strong>son</strong>, the <strong>c </strong>variable environment is going to return and say, let&#39;s find out what the <strong>grandpa</strong> variable is. It&#39;s going to look in the variable environment and it&#39;s going to say — no I can&#39;t find it.</p><p>Now instead of looking in the global scope, or the global variable, it looks in the closure box. And says hey do you have<strong> grandpa</strong> and <strong>father</strong>? And indeed it will find it there.</p><blockquote>The Javascript engine will make sure that the function has access to all the variables outside of the function with this closure. So closure is a feature of Javascript.</blockquote><p>And this is something unique. The Javascript engine will make sure that the function has access to all the variables outside of the function with this closure. So closure is a feature of Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*6cdYniVmwnrXgGgRk1cbWg.png" /></figure><p>From the function above, <strong>function c</strong> is inside of <strong>function a </strong>and <strong>function b. </strong>The Javascript engine is going to create a closure and all the variables outside of the<strong> c function</strong>, it&#39;s going to keep around as long as <strong>c</strong> is using them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*TbnPKphzFJE5Tp6MCvo-CQ.png" /></figure><p>Suppose we had another variable <strong>random</strong>. Here once <strong>b</strong> is invoked, it won&#39;t keep <strong>random</strong> around — it’s going to get garbage collected because nothing is referencing it. But it will keep anything that is being referenced by the child function. So, in this case, <strong>c </strong>still needs <strong>father</strong> and <strong>grandpa</strong> so it&#39;s going to keep it around.</p><p>Closures are also called <strong>lexical scoping</strong>. Lexical meaning where it was written and scoping meaning what variables it has access to.</p><blockquote>Closures are also called lexical scoping. Lexical meaning where it was written and scoping meaning what variables it has access to.</blockquote><p>So by that definition, the Javascript engine before it runs any code, before anything, it already knows which functions have access to which variables.</p><p>Javascript is lexically scoped or <a href="https://www.geeksforgeeks.org/static-and-dynamic-scoping/">statically scoped</a>. During the first phase, it looks through the code and says hey I am going to keep <strong>grandpa </strong>and <strong>father</strong> around even if they get called because I am going to create these scope chains. This is why we can use closures.</p><p>We can have functions that return functions and we have this idea of lexical scope meaning where we write the function matters not where we call the function.</p><h4>Let&#39;s have another example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*TuDp218Kry7_7TK7lRpiCA.png" /></figure><p>Or we can use arrow functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*vyct7i3F3trtBA-nUWkuEg.png" /></figure><p>Now if I run this function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*xizO2gE-iK2aBHyYR4rKxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*2cet2inS0da0u71l4WqqRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*J1qPCuBZ5XA1D0MHIMGl_g.png" /></figure><p>This is one reason closures are powerful. Imagine if we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*18zQDGSEf3UaHuH6pfNqaw.png" /></figure><p>And let&#39;s wait five years. Then do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*mONxQiv1YaDrhIpOoZ96DQ.png" /></figure><p>We could hypothetically wait 5 years if the Javascript engine is running and then finally call<strong> booString </strong>even though the<strong> boo() </strong>function is off the stack.</p><p>It will still remember that this is what we gave it five years ago. That&#39;s because parameters are treated just like local variables that get stored in variable environments.<br>We can wait five years and hold on to information in memory, doesn&#39;t get deleted and I can call it whenever I want.</p><h4>Let&#39;s look at another example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*ca0OQGyzNyK4JEieG10KXA.png" /><figcaption>After 3 seconds, we get a callback</figcaption></figure><p>We have used closures to be able to do this. The function with<strong> setTimeout</strong> gets sent to the <a href="https://en.wikipedia.org/wiki/Web_API">web API</a> to start a timer for 3 seconds. Once the timer is done, we send the function to the callback queue and the callback queue is going to wait there until the call stack is empty.</p><p>So, <strong>callMeMaybe </strong>has been called and it&#39;s now popped off the stack. Now the event loop is going to push this<strong> setTimeout </strong>function onto the stack and run it and <strong>console.log(call me)</strong>.</p><p>Notice variable<strong> callMe </strong>should be gone. <strong>callMeMaybe</strong> has been popped off the stack by the time our function runs. But because of closures, even if the function goes out to the API world, it can still use closures.</p><blockquote>But because of closures, even if the function goes out to the API world, it can still use closures.</blockquote><p>We are able to remember this variable because of closures. <br>Now based on what we know about closures, suppose we remove the variable <strong>callMe</strong> from up there and move it down. What&#39;s going to happen?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*C8Q0m5K7dHU3oCUNUYTW0w.png" /></figure><p>It still works because it doesn&#39;t matter where we define this variable. Even if it’s a <strong>const</strong> that doesn&#39;t get hoisted, we don&#39;t care about hosting here. Instead, our function goes into the web API world, gets put on the<strong> callback queue</strong>, the event loop pushes it back onto the stack. By that time we’ve already created and assigned <strong>const callMe</strong>. And since there is an enclosing function that is using it, it&#39;s going to create a closure.</p><blockquote>Closures can be very memory efficient and allow us to do Encapsulation.</blockquote><h3>Closures and Memory</h3><p>Closures have two main benefits:</p><ol><li>They can be very memory efficient.</li><li>They allow us to do <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">Encapsulation</a>.</li></ol><p>These are the coolest part of closures.</p><p>So how are closures memory efficient? <br>We can start off with a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5CrwiA1uKWfgHCgwv6j-w.png" /></figure><p>Now let&#39;s assume this is a heavy-duty operation that we need to do; let&#39;s assume we are accessing this massive array — indices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*1k1nheL_hwClDM7Eze8lLw.png" /><figcaption>I am accessing index 700 of bigArray.</figcaption></figure><p>Now let&#39;s assume our <strong>index 700</strong> is in a database and gets accessed a lot — so that we call this function many times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*tAzpl9BRQ7Q916fhfKlMpQ.png" /><figcaption>Every time we are creating bigArray and destroying it</figcaption></figure><p>We see here that we are creating <strong>bigArray </strong>, adding data to our memory — which memory is limited, and we are creating the function every time. We are adding this to memory every time and we return it, and because nothing is referencing it, it gets destroyed. Every time!</p><p>That doesn&#39;t look very efficient. Wouldn’t it be great if we could create <strong>bigArray</strong> once? Since we know it’s going to be used a lot, it’s created once and we just have it in memory so that we can just access it instead of doing all that work.</p><h3>How can we do that with closures?</h3><p>Well, let&#39;s create a new function with closures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSuHoV3nYn9cKI_0KGdP4g.png" /><figcaption>We have a reference to bigArray in our returned function hence we have created a closure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OG6D6AywG1nbSGbSp2p-CA.png" /><figcaption>function with closures gets created only once</figcaption></figure><p>We can see the difference here. The first <strong>heavyDuty</strong> was created four times vs <strong>heavyDuty2</strong> where we were able to create <strong>bigArray </strong>only once.<strong> </strong>Because we knew we were gonna access it a lot, we just maintained that closure scope over it and we were able to call it over and over without doing all that creation — destruction work.</p><h3>Encapsulation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsmB917H62KLci3ZFSEODA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*Jm2MXwfsD3zfMtJPyiWD9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*CN_0a6H-zFd9NTp85vZtBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*eT3gzqdWaXoycZUsNtGV-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*qVuLZFPjA1rYXebTWwTfNw.png" /></figure><p>Here we used closures. The <strong>timeWithoutDestruction</strong> is something that all these functions have access to. But we also wouldn&#39;t want people to have powers to<strong> launch</strong>. So let&#39;s remove the launch function from the returned object and instead just have <strong>totalPeaceTime</strong>.</p><p>So that if try to launch, I get an error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8oo8WrVcUVNf5ypJDiW5Q.png" /></figure><p>This is what encapsulation does. It&#39;s hiding information that is unnecessary to be seen by the outside world or information that can be manipulated.</p><p>This gets into the idea of the principle of least privilege — a big security principle when it comes to programming. Here you don’t want to give anybody access to your API, your special functions, or variables.</p><p>By using closures we are able to access things like <strong>timeWithoutDestruction </strong>that I don’t want anybody accessing because I just want setInterval to constantly increment that. But at the same time, I still want people to access things like <strong>totalPeaceTime</strong> so that that <strong>totalPeaceTime</strong> can access the variables that are sacred to me. And this is one of the main benefits of closures — data encapsulation. It refers to the idea that some data shouldn&#39;t directly be exposed.</p><p>Modules in Javascript especially classical module patterns that people used to use with IIF, use this pattern and we are only able to do that because of closures.</p><h3>Let&#39;s look at another example.</h3><p>How can the function below be called only once so that we can avoid someone abusing it and run it a bunch of times? We want our function to run only once, no matter how many times its called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUHyK2UagVu3CyAKkwSQZA.png" /><figcaption>Our display is set thrice. We would prefer to have it set once</figcaption></figure><p>So how can we fix this using what we know about closures?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*uM5AzURsOYII2TZG3jXMjg.png" /><figcaption>Now it doesn’t matter how many times I call my function, it will only run once.</figcaption></figure><h3>Let&#39;s look at another example</h3><p>This has to be one of the most common interview questions for Javascript developers and there are two ways of solving this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*kccOfpVHhmVxtzGk2qlP3Q.png" /></figure><p>Now if I run this function I will get<strong> I am at index 4</strong> logged 4 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*I9B3U4434fbMlK-FfHPYTg.png" /></figure><p>The easiest way is to change the <strong>var </strong>keyword to <strong>let</strong> because <strong>let </strong>allows us to use block scoping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meT17NM-qGs4LsHP7EnjTw.png" /><figcaption>let allows us to use block scoping unlike var</figcaption></figure><p>With <strong>let</strong>, the curly brackets create scope for each <em>i</em>. Note that initially with <strong>var</strong>, <em>i</em> was part of the global scope. We didn’t have a function surrounding it. So that when the <strong>setTimeout</strong> finally returned, the for loop had already gone through everything and turned <em>i</em> into 4.</p><p><strong>But what if we couldn&#39;t use the Let keyword?</strong></p><p>We can use closures to wrap <strong>setTimeout</strong> into an immediately invoked function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kGbaRrGW77QK6DbEt8n3w.png" /></figure><p>Here as long as we reference <em>i </em>in the function, because of closures it won&#39;t be removed from the local scope.</p><p>We do that by passing this immediately invoked function parameter <em>i ; </em>So that with parameter <em>i every time</em> it loops, we will be incrementing 0,1,2…</p><p>We receive the <em>i </em>in our function as <strong>closureI</strong>(Just to keep the name separate)and we can access it with the array as well as <strong>array[closureI]</strong></p><p>To summarise,<br>we have seen an important pillar of Javascript — closures. We have learned that a closure is the combination of a function and a lexical environment in which it was declared.</p><p>We are able to create closures in Javascript because functions are a first-class citizen and we have Lexical scope.</p><p>Therefore the statement we made earlier that, “Closures allow a function to access variables from an enclosing scope or outer scope environment even after it leaves the scope environment in which it was declared” makes sense. Because as we have seen, all that matters in Javascript is where the function was written.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e7ed96f241c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/all-you-need-to-know-about-closures-the-first-pillar-of-javascript-5e7ed96f241c">All you need to know about Closures — The first pillar of Javascript.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Concepts in Javascript — Higher Order Functions(HOF)]]></title>
            <link>https://medium.com/swlh/advanced-concepts-in-javascript-higher-order-functions-hof-ecd673a2a3f7?source=rss-36e7c437b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecd673a2a3f7</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[myjavascriptjourney]]></category>
            <dc:creator><![CDATA[Allan Sendagi]]></dc:creator>
            <pubDate>Sat, 02 May 2020 03:29:47 GMT</pubDate>
            <atom:updated>2020-05-05T07:03:10.621Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Concepts in Javascript — Higher Order Functions(HOF)</h3><h4>The art of making our code more general and avoid repeating ourselves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeJLT6vvcOqwPNIMsLvDZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mischievous_penguins?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Casey Horner</a> on <a href="https://unsplash.com/s/photos/stairs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Let&#39;s start off by reviewing our knowledge of functions.</p><p>We know that functions in Javascript are objects.<br>We also said that when we invoke a function, we get two parameters automatically:<strong> this </strong>keyword and<strong> arguments</strong> keyword.</p><p><a href="https://medium.com/@allansendagi/javascript-foundation-function-invocation-arguments-keyword-variable-environment-scope-chain-97d4888cf319">Javascript Foundation — Function Invocation, Arguments keyword, Variable environment, Scope chain.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*Lzt0sQqe4jsjoNF-.png" /><figcaption><a href="https://zerotomastery.io/">source: ZTM Academy</a></figcaption></figure><p>We saw that <strong>arguments</strong> is an array-like object with weird behaviors for looping and iteration, so we want to avoid using it. Instead, we can use something like the spread operator.</p><p>We also learned that because of the <strong>arguments</strong>, we can have a function with no parameters defined but we can call it with parameters and still grab them using the arguments keyword.</p><p>We saw that when we define our functions, the compiler looks at our code lexically and determines what variables are available for us in our variable environment and also adds scope chains.</p><p><a href="https://medium.com/@allansendagi/javascript-foundation-function-invocation-arguments-keyword-variable-environment-scope-chain-97d4888cf319">Javascript Foundation — Function Invocation, Arguments keyword, Variable environment, Scope chain.</a></p><h3>Function invocation</h3><p>We saw a few ways of invoking functions.</p><ol><li>The first method we are very familiar with.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*GdKFal670QSWYk-6SPvk0Q.png" /></figure><p>2. The second way we saw is as a method. A method is a function inside of an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*vr67_BmEf-DzIPQNI9oYVw.png" /></figure><p>We can simplify this function with the new <a href="https://github.com/daumann/ECMAScript-new-features-list/blob/master/README.md">ECMA script</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*BM6pSTpX8Yq-PI9jNwonXw.png" /></figure><p>Notice that here obj is calling <strong>two()</strong>, the <strong>this</strong> keyword is updated to<strong> obj</strong> instead of<strong> </strong><a href="https://www.w3schools.com/jsref/obj_window.asp"><strong>window</strong></a><strong>.</strong></p><p>3. The third way to use functions is to use call.</p><p><a href="https://medium.com/@allansendagi/javascript-fundamentals-call-and-apply-997d79dfa336">Javascript Fundamentals: call() and apply()</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*h-V90XD30tK40RY991CLSQ.png" /></figure><p>4. Those are the three main ways but there is one more way you won&#39;t see very often.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Kal3HSFqheF51GcYw5nVgA.png" /></figure><p>This is called a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function">function constructor</a>.</p><p>Our built-in objects that the Javascript language comes with create functions for us. Here the first parameter is whatever we want the function task to be — which is to return 4.</p><p>But we can also have parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*CGjhTBcmDMSTzGQnYxl3GQ.png" /></figure><p>I still get four. <br>Whatever is in the last parameter of the function will be the actual code body.</p><h3>Functions are objects.</h3><p>This is something not very common in other languages. In Javascript, I can do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*lC2-_bpd2WpDWPh8AEYz5Q.png" /><figcaption>We’ve added a property to a function</figcaption></figure><p>Underneath the hood what Javascript does is it creates a special type of object called a <strong>Callable Object</strong>. Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*w6oW9mhlw9B_ZB2nsLjZlw.png" /><figcaption>The callable object can be invoked</figcaption></figure><p>This code, of course, wouldn&#39;t work. It’s pseudocode to show you what&#39;s going on underneath the hood.</p><p>To summarise, if we had a function<strong> someFunc()</strong>, it would be an object with 3 special properties:<br><br>1. <strong>code()</strong>: It would have a piece of code that we can invoke with the two brackets. When we invoke with these brackets, it reads whatever the piece of code is in those brackets and executes it.</p><p>2. <strong>Name</strong>(optional): If for example the function was called <strong>someFunc</strong>, the name would be <strong>someFunc</strong>. But remember we also have anonymous functions.<br>If we used function expression, assign it to a<strong> var</strong> but the function itself is anonymous, well, the name wouldn&#39;t exist because it&#39;s optional.</p><p>3. <strong>Properties</strong>: We get properties automatically on a function. We have properties like<strong> call()</strong>, <strong>apply()</strong> and <strong>bind()</strong> that allow us to operate upon that function.</p><p>For example, if I go back to woohoo,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*Pj1_4pRBBr8uQx8y-u_MAQ.png" /><figcaption>We have the <strong>call() </strong>method available to us.</figcaption></figure><p>We also have properties like<strong> arguments</strong>,<strong> length</strong>, <strong>name</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*dv4NpW1mK7DWKXRpF31kew.png" /></figure><h3>Objects</h3><p>With objects, I don’t have the same properties and methods that we have seen such as <strong>call()</strong>,<strong> bind()</strong>, <strong>apply() </strong>or any of the properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*7PBXK2PONEKhXvJdSnLv0A.png" /></figure><p>Remember functions are objects — but they are a special type of object. A callable object with a bracket notation for invoking a function, contains code, it has name and it also has some properties like call, apply and bind.</p><h4>Why is this important?</h4><p>Since functions are just objects in Javascript, we can pass them around like objects, or things that contain data.</p><p>So besides just doing things for us, and performing actions on our code, we can also store them as data, move them around and have some really interesting applications.</p><h3>First-class citizen</h3><p>Since functions can be passed around like data, besides just performing actions on our code, you will hear people say that functions are a first-class citizen in Javascript.</p><p>This means three things:</p><ol><li>Functions can be assigned to variables and properties of objects.<br>So that I can do:</li></ol><p><strong>var stuff = function(){};</strong></p><p>In some languages, I can’t do that. I can just run functions to perform actions and that&#39;s it. In Javascript, I can assign it to a variable or an object property which then becomes a method.</p><p>2. We can also pass functions as arguments into a function. So I can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*as2kXAz3Pl0vj7VHlhFnJg.png" /><figcaption>Here we are able to pass a function as a parameter to a function.</figcaption></figure><p>3. We can return functions as values from other functions. What does that mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*UhcoDsP1Y7hun-LVYknejQ.png" /></figure><p>Or I can assign it to a variable and then just call that var d.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*ogLsoXBT5C_Ggt6A38lOGw.png" /></figure><p>So those are the three properties that make functions a first-class citizen in Javascript. We are able to assign these functions to variables, we can pass these functions into arguments and we can also return functions as values from other functions.</p><p>So functions are data because not only do they perform actions for us but they can be passed around as if they were Javascript types. So anything you can do with other types, you can do with a function.</p><p>This idea of a first-class property introduces Javascript to a whole world called <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a>.</p><h3>Things to avoid while using functions</h3><ol><li>Avoid initializing functions inside loops.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*kz5ZzLpRy8RCaiqkbXI23Q.png" /></figure><p>Here every time we loop, for example when <em>i=0</em>, we are going to initialize the <strong>function a</strong>, and then run it. Same when<em> i=1, </em>we will initialize <strong>function a </strong>and then invoke the function and so on.</p><p>Instead of initializing the function inside of a loop, we should be moving the function up top. So that we initialize the function just once. When we loop over it, we are just executing it five times instead of initializing it and executing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*KL4-6d-VfOv6DpaUlaDe9w.png" /></figure><p>2. Here another thing we should be careful of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*1aQvE4FgqEHos_u4NjnUFQ.png" /></figure><p>My function gives me a reference error because <strong>param</strong> is neither in the local or global scope.</p><p>As soon as we have nothing in our variable environment or scope chain, we get a reference error. <br>Now, this normally causes a lot of functions to fail and involves us always doing some sort of a check to see if the <strong>param</strong> exists.</p><p>We could, of course, add a <strong>param</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*SKLTMiJEuv_eL73ybAV6Hw.png" /></figure><p>So that if I run this I won&#39;t get that error. In this case, the <strong>param </strong>is added automatically to our variable environment as if we just declared that variable.</p><p>But when we call it with nothing, we just get undefined. One way to avoid this is if you just give it a default parameter which came with Es6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*sPmAStcf201KTLyjxcnLjg.png" /></figure><p>Now if I run this, instead of undefined I get 6. So its good to have default parameters set as a way to avoid these edge cases.</p><h3>Higher-Order Functions</h3><p>HOF are functions that can take a function as an argument or a function that returns another function.</p><h4>Why should we care about HOF?</h4><p>First, let&#39;s look at the problems we can solve with just <strong>a function.</strong></p><p>Suppose we have a company system that lets our users log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*zHQpdZsUnH5OZhVFNwb_SQ.png" /><figcaption>useless code to demonstrate authentication</figcaption></figure><p>With this function, there is a lag — it takes time to grant access to adam. And if we add another zero, things will be very slow.</p><p>Now, remember we are assuming that this is an authentication service that our company has. But what if we have more employees we want to authenticate.</p><p>Let&#39;s say we have Eva.<br>We will have to create another authentication function for Eva.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*QlC5BDX_dhtzlCxjnRGqtw.png" /></figure><p>But now we have a problem with this code; Don’t we? We aren’t keeping our code DRY. We are repeating ourselves. The code we have created is not flexible.</p><p>For each user that we have, we have to copy and paste code and repeat ourselves. Just imagine if we had hundreds and hundreds of employees, doing this every time would not be inefficient.</p><h4>So how can we fix this?</h4><p>Let&#39;s move on from a single function to a function that accepts parameters.</p><p>So instead of having <strong>letAdamLogin </strong>&amp; <strong>letEvaLogin</strong> functions, lets create a generic function<strong> letUserLogin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*TsUml3JCiDg5rg331aCjiw.png" /><figcaption>I will get access granted to Adam.</figcaption></figure><p>And for Eva:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*-pPWfsH6EaFXYiYggS2VmQ.png" /><figcaption>I will get access granted to Eva.</figcaption></figure><p>Now, let&#39;s refactor the code to make it cleaner by creating another function <strong>giveAccess.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*NA6FtDyFlwEpY8u5G8o8Yw.png" /></figure><p>So I can just return <strong>giveAccessTo</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*1lOnPiOQsBceCuK6odBI9w.png" /></figure><p>We have leveled up here. Now we tell the function what data to use when we call it.</p><p>Remember before our function whenever we called it decided what to do with that data. Instead, we now have a more generic function that says hey I am going to give you some generic piece of data I don&#39;t know what yet but when I pass you the user do some sort of functionality to it.</p><p>So that instead of defining <strong>Eva</strong> or <strong>Adam</strong> inside of a function, we can just define that later on when we just invoke the function</p><p>So we have the ability to define the data when we call the function. We have a little bit of flexibility. We kept our code DRY.</p><h4>But what are the limitations here?</h4><p>What if instead of just users we also have admin — Somebody with a lot more privilege?</p><p>Then we would have to copy the code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*rg3JExmt7NEuI4EDUZ06QA.png" /></figure><p>Now you have noticed here that since its admin, we have to go through a bit more procedures hence the “5000000” — let&#39;s say it takes a bit more time for them to get authenticated.</p><p>So the function has changed a little bit — we have a different permission process. But still, we just copied more code. We are not being very DRY. <br>And imagine if we had to give access to managers, secretaries, guest access and so on.</p><h4>So what can we do here?</h4><p>This is where higher-order functions can come into play.</p><p>Remember we went from simple functions <strong>function() </strong>to functions with parameters<strong> function(a,b)</strong>. This meant that instead of just defining the function and telling it exactly what to do and what data to use, we are able to define what the function does but later on, when we call the function, we tell it what data we need.</p><p>With a higher-order function, we get to do both of those things when we call the function. We can give the function data but also tell it what to do or some extra abilities when we actually invoke it.</p><h4>So how would this work?</h4><p>First, let&#39;s create an authenticate function that takes a parameter — in our case a number which is the time of authentication. This is the verification process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NA6FtDyFlwEpY8u5G8o8Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*1pmBPeJPpowErICbmY3Q4g.png" /><figcaption>We have verified everything, you can have access — return true</figcaption></figure><p>We have the <strong>authenticate </strong>and <strong>giveAccess </strong>functions. Now how can we make the rest of the functions better?</p><p>Let&#39;s remove let the <strong>letUserLogin</strong> and <strong>letAdminLogin</strong> functions and instead let&#39;s create a general function <strong>letPerson.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*HfQLjnMmlX2gwBpUBuzT1Q.png" /></figure><h4>So how did this make things easier?</h4><p>Now we can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*QHc8F0P82ZbJWznaqVMmhw.png" /></figure><p>It works.<br>And if I change to admin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQl_EfeEAdEIUPyjDx9m4w.png" /></figure><p>That also works.</p><h4>So what power did we just gain here?</h4><p>Now we have the power to not only tell it what power to use, but also what to do.</p><p>We created a generic function <strong>letPerson</strong> compared to the previous <strong>letAdamLogin</strong>. It was too specific. <strong>letPerson </strong>accepts the person as the first parameter and then a function, in this case, <strong>authenticate</strong> as a second parameter.</p><p>So by making things general, we can now add something like a sing function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*i9aUXaHDIHrYGugBnZfRuw.png" /></figure><p>Our <strong>letPerson</strong> function is more general now — it’s a higher-order function because it accepts a function as a parameter, I can now add many more functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*89KqPlWTe84hKaP5tIfUAg.png" /></figure><p>We removed <strong>giveAccessTo</strong> function and added it to the <strong>authenticate </strong>and we just returned some generic functions in <strong>letPerson </strong>to have this work.</p><p>What we have been able to achieve with higher-order functions is this ability to tell a function what to do during invocation; we are able to have more flexibility than we had before and we avoid repeating ourselves.</p><p>Let&#39;s have one last example. Let&#39;s create a generic multiply function so that I am able to create multiple functions from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*jqff5_BGH9rjQufbyGDs8g.png" /></figure><p>With this in place, I can now store my function in another variable let&#39;s say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*UGq3w5b7d5GBV3TPoCPOQA.png" /></figure><p>Now I have this functionality that I can keep reusing where I can:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*KNTzd4uI6NKvV_3ax5ZtzA.png" /><figcaption>2*4=8</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*vpvoYtDfA4kAzaLX8-27ig.png" /><figcaption>2*10=20</figcaption></figure><p>I can have this functionality over and over with this higher-order function.</p><p>Here the<strong> multiplyBy</strong> is a higher-order function because it returns another function.</p><p>I can also extend this where I can do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*yJYIKG_9jHLG09OY38Q_8A.png" /><figcaption>6*5=30</figcaption></figure><p>We can also use arrow functions to write this in a much cleaner way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*sCGkOvEXtSmHbL5HGBsR3g.png" /><figcaption>Arrow functions visually make sense.</figcaption></figure><p>All its saying is:<br>Give me a parameter then another parameter. So if I just do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*DW7zhQ-3KNZldrrl5Fz2lg.png" /><figcaption>4*6=24</figcaption></figure><p>And that&#39;s all these brackets are showing you and by now I hope we can see the power of HOF.</p><p>We learned how to go from a simple <strong>function() </strong>to a function with parameters<strong> function(a,b) </strong>to higher-order functions.The main benefit is we are able to make our code more general — DRY, we don’t repeat ourselves and we have the ability to break things down into more functionalities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecd673a2a3f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/advanced-concepts-in-javascript-higher-order-functions-hof-ecd673a2a3f7">Advanced Concepts in Javascript — Higher Order Functions(HOF)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>