<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Blossom Babs</title>
    <description>The latest articles on DEV Community by Blossom Babs (@blossom).</description>
    <link>https://dev.to/blossom</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F368451%2Faead7aa6-4442-4850-bd74-dd9e47c6fff7.jpeg</url>
      <title>DEV Community: Blossom Babs</title>
      <link>https://dev.to/blossom</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/blossom"/>
    <language>en</language>
    <item>
      <title>8 Best Practices for React.js Component Design</title>
      <dc:creator>Blossom Babs</dc:creator>
      <pubDate>Mon, 17 Jul 2023 09:26:00 +0000</pubDate>
      <link>https://dev.to/blossom/8-best-practices-for-reactjs-component-design-4jn5</link>
      <guid>https://dev.to/blossom/8-best-practices-for-reactjs-component-design-4jn5</guid>
      <description>&lt;p&gt;React is one of the most popular JavaScript libraries for building user interfaces, and one of the reasons it gained so much popularity is its Component-Based Architecture. React encourages building UI in reusable components, allowing developers to build complex user interfaces more efficiently.  &lt;/p&gt;

&lt;p&gt;Since we would be dealing with components in react, it is essential to follow best practices for component design. In this article, we'll explore 10 best practices that will help you write cleaner, more maintainable, and reusable React components:&lt;/p&gt;

&lt;p&gt;1 - &lt;strong&gt;consistent formatting:&lt;/strong&gt; There are several ways to create a functional component in a react application, some of them include - arrow functions, functions declarations and function expression. All of these are valid ways to create a component but it is important to stick with 1 way of declaring a component in your application. Inconsistent component functions can make your code difficult to read.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft3iexha2sobd9ml1i5vb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft3iexha2sobd9ml1i5vb.png" alt="function declaration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6m3uub5hc7mf2skk40p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6m3uub5hc7mf2skk40p.png" alt="function expression"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F33h2vwfudpiihkdxz4t2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F33h2vwfudpiihkdxz4t2.png" alt="arrow function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2 - &lt;strong&gt;Follow a design pattern and stick to it:&lt;/strong&gt; Following an already established design pattern in your react application keeps your components organised, easy to read, test and make changes. Two of already established practices include:&lt;/p&gt;

&lt;p&gt;a. Container/Presentational Pattern: Following this approach ensures a strict separation of concern between the business logic and user interface. Where the container components manages data and state, while presentational components focus on rendering the UI.easier to test.&lt;/p&gt;

&lt;p&gt;b. Flux Pattern: Flux pattern was introduced by the facebook team to introduce a unidirectional data flow in your react application, this is commonly enforced using state management libraries like redux.&lt;/p&gt;

&lt;p&gt;3 - &lt;strong&gt;Single Responsibility Principle:&lt;/strong&gt; Each component in your app should have a single responsibility, focusing on one specific functionality. Following this principle makes the component more reusable and less prone to bugs. For example, in most cases, a "Button" component should handle ONLY rendering and user interactions.&lt;/p&gt;

&lt;p&gt;4 - &lt;strong&gt;Prop Types and Default Props:&lt;/strong&gt; Defining prop types and default values ensures component reliability. PropTypes validate the expected types of props, catching potential bugs early. Default props provide fallback values if a prop is not explicitly passed, avoiding unexpected behaviour. &lt;/p&gt;

&lt;p&gt;Do not use typescript in your project? This is totally fine, you can still achieve this using the propTypes library.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install --save prop-types&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import PropTypes from 'prop-types';

Button.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
};

 function Button(props) {
  const {name, age} = props
  return (
    &amp;lt;div className='App'&amp;gt;
      &amp;lt;h1&amp;gt;Hello {name}&amp;lt;/h1&amp;gt;
      &amp;lt;h2&amp;gt;I am {age}&amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default Button;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;5 - &lt;strong&gt;Destructuring Props:&lt;/strong&gt; Take advantage of the object destructing to access props. This can reduce verbosity in the code and enhance readability. It also improves the clarity of component interfaces and makes it easier to identify which props are used.&lt;/p&gt;

&lt;p&gt;An example of this can be seen in the Button component code shared above: &lt;code&gt;const {name, age} = props&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;6 - &lt;strong&gt;Prop and state:&lt;/strong&gt; It is crucial to understand the difference between your props and your state. Props are static data passed around within components. They are immutable and do not change. State is used to manage dynamic data within a component. It represents the internal state of a component, allowing it to handle and respond to user interactions, events, or changes in the component's own logic.&lt;/p&gt;

&lt;p&gt;7 - &lt;strong&gt;Styling:&lt;/strong&gt; Styling is an important aspect of React component design. The most important thing here is to pick a styling of choice and remain consistent with it across components in the library. Some of the most popular styling choices include:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use CSS-in-JS libraries: CSS-in-JS libraries like styled-components can make it easier to style your components and create reusable styles.&lt;/li&gt;
&lt;li&gt;Use CSS modules: CSS modules allow you to create component-level styles that don’t clash with styles from other components.&lt;/li&gt;
&lt;li&gt;Use utility-first CSS framework like tailwind css&lt;/li&gt;
&lt;li&gt;Use UI libraries such as material-ui, ant design, chakra etc.&lt;/li&gt;
&lt;li&gt;Create reusable styles: When creating custom styles with css, sass etc. It is important to prioritise reusable styles that can be used across your application. This can help you create a consistent visual style and make your components more maintainable.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;8 - &lt;strong&gt;Testing:&lt;/strong&gt; Testing is perhaps one of the most severely underrated aspects when it comes to building react components. Here are some best practices to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use libraries like Jest and cypress to write unit tests for your components.&lt;/li&gt;
&lt;li&gt;Test props and state: Test that your components handle props and state correctly. This can help you catch bugs that might not be apparent in the UI.&lt;/li&gt;
&lt;li&gt;Test end to end user interactions: Test that your components handle user interactions correctly. This can help you ensure that your components are user-friendly and responsive.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conclusion:
&lt;/h3&gt;

&lt;p&gt;By following these best practices for React component design, you'll be able to create cleaner, more maintainable, and reusable components. Each practice reinforces important principles such as single responsibility, reusability, prop validation, and performance optimisation. Incorporating these practices into your React projects will contribute to better code quality, improved developer experience, and ultimately, more robust applications.&lt;/p&gt;

&lt;p&gt;Remember, mastering these best practices requires practice and continuous learning. Stay up-to-date with the evolving React ecosystem and always strive for code that is efficient, readable, and easy to maintain.&lt;/p&gt;

&lt;p&gt;Happy coding ☕️&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Mocking vs Stubbing</title>
      <dc:creator>Blossom Babs</dc:creator>
      <pubDate>Tue, 02 May 2023 09:32:28 +0000</pubDate>
      <link>https://dev.to/blossom/mocking-vs-stubbing-2d43</link>
      <guid>https://dev.to/blossom/mocking-vs-stubbing-2d43</guid>
      <description>&lt;p&gt;𝐌𝐨𝐜𝐤𝐢𝐧𝐠 !== 𝐒𝐭𝐮𝐛𝐛𝐢𝐧𝐠&lt;/p&gt;

&lt;p&gt;When it comes to testing your react applications, we typically do not test the actual API calls, we instead use test doubles &lt;/p&gt;

&lt;p&gt;Test doubles is the general term for defining objects that are not real. Mocks and stubs are a part of a class of test doubles. They are a kind of pretend  object used in place of a real object for testing purposes. This term includes dummy, fake, stub and mock.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mocking and stubbing are often used interchangeably but they are not the same.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;They both involve using fake objects to manage and isolate side effects. Mocking and stubbing are two software techniques used to create controlled and predictable environments for testing code, but they differ in their approach and purpose.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Mocking&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;This is the technique of creating a fake object that mimics the behaviour of a real object, typically for the purpose of testing interactions between objects. Mock objects verify that the tested code correctly 𝐜𝐚𝐥𝐥𝐬 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 𝐨𝐧 𝐭𝐡𝐞 𝐦𝐨𝐜𝐤𝐞𝐝 𝐨𝐛𝐣𝐞𝐜𝐭 and that the expected results are returned.&lt;/p&gt;

&lt;h2&gt;
  
  
  Stubbing
&lt;/h2&gt;

&lt;p&gt;On the other hand, is the technique of creating a fake object or function that returns 𝐩𝐫𝐞𝐝𝐞𝐟𝐢𝐧𝐞𝐝 𝐯𝐚𝐥𝐮𝐞𝐬, typically for the purpose of testing specific code paths. Stub objects are used to simulate the behaviour of a real object or function, but without actually performing the full functionality. Stubbing is often used to test error handling, and edge cases, or to isolate a specific piece of code for testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some of their Key differences include:&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Style
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Mocks&lt;/strong&gt; tests for the behaviour of the unit&lt;br&gt;
&lt;strong&gt;Stubs&lt;/strong&gt; tests for the state of the unit&lt;/p&gt;

&lt;h2&gt;
  
  
  Principle
&lt;/h2&gt;

&lt;p&gt;According to the principle of testing only one thing per test, there may be several stubs in one test, but generally, there is only one mock.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lifecycle
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Test lifecycle with stubs:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Setup - Prepare the object that is being tested and its stubs collaborators.&lt;/li&gt;
&lt;li&gt;Exercise - Test the functionality.&lt;/li&gt;
&lt;li&gt;Verify state - Use asserts to check the object's state.&lt;/li&gt;
&lt;li&gt;Teardown - Clean up resources.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Test lifecycle with mocks:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Setup data - Prepare the object that is being tested.&lt;/li&gt;
&lt;li&gt;Setup expectations - Prepare expectations in mock that are being used by the primary object.&lt;/li&gt;
&lt;li&gt;Exercise - Test the functionality.&lt;/li&gt;
&lt;li&gt;Verify expectations - Verify that correct methods have been invoked in mock.&lt;/li&gt;
&lt;li&gt;Verify state - Use asserts to check the object's state.&lt;/li&gt;
&lt;li&gt;Teardown - Clean up resources.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Practical use-case
&lt;/h2&gt;

&lt;p&gt;Mocking makes sense to assert navigation within React app. In the integration test we could create a mock of the navigate function and spy on whether it was called at a certain time while interacting with the page.&lt;/p&gt;

&lt;p&gt;Stubbinng is more popular, especially stubbing the state of out-of-process dependencies like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An API request&lt;/li&gt;
&lt;li&gt;Operation on browser cookies&lt;/li&gt;
&lt;li&gt;An interaction with an external SDK&lt;/li&gt;
&lt;li&gt;Operations on the URL in the browser&lt;/li&gt;
&lt;li&gt;An interaction with a Web Storage (local/session storage)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Da9JBz7r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abz2okmc0y65wzgd36lb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Da9JBz7r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abz2okmc0y65wzgd36lb.png" alt="A practical implementation of mock" width="800" height="1000"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>testing</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>React update 2020</title>
      <dc:creator>Blossom Babs</dc:creator>
      <pubDate>Wed, 30 Dec 2020 10:57:44 +0000</pubDate>
      <link>https://dev.to/blossom/react-update-2020-jib</link>
      <guid>https://dev.to/blossom/react-update-2020-jib</guid>
      <description>&lt;p&gt;React 2020 is here! Here are two new features I have noticed so far:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. You no longer have to import React and ReactDOM.
&lt;/h2&gt;

&lt;p&gt;I quite liked this for some reason; less code. Also, my js files have the extensions &lt;strong&gt;js&lt;/strong&gt; and my jsx files have the extension &lt;strong&gt;jsx&lt;/strong&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. reportWebVitals.js
&lt;/h2&gt;

&lt;p&gt;reportWebVitals has replaced serviceWorker. serviceWorker.js is used to make the react app a progressive web app. However, it has been replaced with reportWebVitals.&lt;/p&gt;




&lt;p&gt;Have you started using the new react update? Do you like it? What new features have you noticed? Let me know in the comment section below 👇🏾&lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>Build responsive websites without a framework</title>
      <dc:creator>Blossom Babs</dc:creator>
      <pubDate>Sun, 13 Dec 2020 17:59:47 +0000</pubDate>
      <link>https://dev.to/blossom/build-responsive-websites-without-a-framework-47e6</link>
      <guid>https://dev.to/blossom/build-responsive-websites-without-a-framework-47e6</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;Summary&lt;/strong&gt;: Responsiveness is fundamental in web development. With multiple devices and screen resolutions, you want to build a website that works on ALL these screens. In this article, I would be taking you through five things you &lt;strong&gt;must&lt;/strong&gt; consider when building a responsive website without a framework.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  What is Responsive Web development?
&lt;/h1&gt;

&lt;p&gt;Responsive web development is an approach to web design that makes web pages render well on a variety of devices and screen sizes. Web development has advanced past simply designing static pages for the computer. Now, your web pages and applications have to support multiple devices viewport; there are lots of them.&lt;/p&gt;

&lt;p&gt;Every frontend developer has heard or read the above multiple times. Responsive web development was one of the first things that I heard over and over again. However, I was introduced to bootstrap for responsiveness.&lt;/p&gt;

&lt;p&gt;There are lots of CSS frameworks, However Bootstrap was one of my favourite frameworks to use. I used bootstrap in all my projects including react based projects for responsiveness till I realised I was overly dependent on it. Also, Bootstrap can have a lot of dependencies in instances of small-scale projects.&lt;/p&gt;

&lt;p&gt;In my journey to build fully responsive without frameworks and with just HTML and CSS, I found out 5 crucial things to do to make sites responsive and developments less cluttered.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Always design mobile-first
&lt;/h2&gt;

&lt;p&gt;Contrary to popular opinion, this is not gate-keeping. Designing mobile-first ensures that you are able to get as much information as you can on a smaller screen. When it is scaled up, the components would scale up too. However, if you design for desktop first, most components will go out of place when shrinked down for  a smaller sized screen.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a challenge; you should replicate a simple landing page. Build mobile first then desktop first, see which was easier to scale.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Define a fluid layout
&lt;/h2&gt;

&lt;p&gt;My go-to keywords for defining the overall layout of the webpage are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;width: 90%;
margin: 0 auto;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The width ensures that everything on the web page is a set width from the border of the screen size. Margin sets the content of the webpage to the center of the screen width.&lt;/p&gt;

&lt;p&gt;You can play around with the width depending on what you need.&lt;/p&gt;

&lt;p&gt;Make sure you use percentage to define the width, this is because percentages are fluid and will adjust to the size of the device viewport.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a challenge; you should add width and margin to the landing page you created above. It would make the scaling up or down much more fluid.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Know when to use Rems and Ems
&lt;/h2&gt;

&lt;p&gt;Rems and Ems are size units just like pixels and percentages. Rems and Ems are relative units and are much more preferred when defining font size, border, padding etc.&lt;/p&gt;

&lt;p&gt;They are very different though.&lt;/p&gt;

&lt;p&gt;Em is relative to the size of its direct or nearest parent, while Rem is only relative to the html (root) font-size.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.body{
font-size: 14px;
}

.container{
width:50%;
background-color:red;
font-size: 1.5em;

h1{
font-size: 3em;
}

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;h1{font-size:3rem;}&lt;/code&gt;&lt;br&gt;
&lt;code&gt;h1{font-size:3em;}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a challenge, run both codes or variations of it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Both h1 sizes would differ. The em unit will be relative to its parents element(the container); the h1 will be three times the size of the container.&lt;br&gt;
While the rem unit will be relative to the body, not the parent.&lt;/p&gt;

&lt;p&gt;When using units, you want to know when to use which so as to avoid cascading effect.&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Use CSS layouts
&lt;/h2&gt;

&lt;p&gt;Grid and Flex are powerful tools for structuring the layout of the web. Use them!&lt;/p&gt;

&lt;p&gt;Once I found out how similar the bootstrap grid was to css native grid and flex, there simply was no going back for me. Infact I find the css grid much simpler, customizable and with no dependencies.&lt;/p&gt;

&lt;p&gt;If for some reason, I have to use the Bootstrap framework, it would definitely not for the layouts.&lt;/p&gt;
&lt;h2&gt;
  
  
  5. Use media queries
&lt;/h2&gt;

&lt;p&gt;When I started writing responsive designs without frameworks, I used media queries everywhere.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media and screen(max-width: 500px){
//
}

@media and screen(max-width: 320px){
//
}

@media and screen(max-width: 480px){
//
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It was a mess and this is why I have saved this for last.&lt;/p&gt;

&lt;p&gt;It is impossible not to use media queries when talking about responsiveness. But, if you take note of the points above, you wouldn't need media queries for every breakpoint. Instead, they would be used sparingly and specifically. E.g, the point where the screen goes from being a phone to tablet and tablet to laptop and laptop to the television. Not for every brand of iPhone viewport.&lt;/p&gt;

&lt;p&gt;Familiarize yourself with the use of width and max-width. The width can be used to set the width for a screen, then max-width for lager screens all in the same block of code. Neither affecting the other.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bonus point&lt;/strong&gt;: Avoid setting a fixed width and height for your image. Either set width or height, it would scale up nicely and responsively. Setting a width and height distorts it and makes it unresponsive.&lt;br&gt;
Pro-tip: Use a percentage to define the widths.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>html</category>
      <category>css</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Understanding the basics of Javascript reduce method</title>
      <dc:creator>Blossom Babs</dc:creator>
      <pubDate>Wed, 13 May 2020 11:56:00 +0000</pubDate>
      <link>https://dev.to/blossom/understanding-the-basics-of-javascript-reduce-method-54kn</link>
      <guid>https://dev.to/blossom/understanding-the-basics-of-javascript-reduce-method-54kn</guid>
      <description>&lt;p&gt;Here is a basic explanation of how the Javascript reduce() method works.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const evenNums = [2, 4, 6, 8]
evenNums.reduce((accumulator, currVal) =&amp;gt; accumulator + currVal)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above is the most basic (simplest) form you would see the reduce() method being used.&lt;/p&gt;

&lt;p&gt;The above example also makes use of the es6 const and arrow function. Let's take an example using the normal function keywords and var, then break it down.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var evenNums = [2, 4, 6, 8]
evenNums.reduce( function (accumulator, currVal){
    return accumulator + currVal
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright.&lt;/p&gt;

&lt;p&gt;In the first line of both codes given above, a variable is declared &lt;em&gt;const&lt;/em&gt; and &lt;em&gt;var&lt;/em&gt;, then they are both named as &lt;em&gt;evenNums&lt;/em&gt;, then an array is assigned to this named variables (&lt;em&gt;an array of even numbers&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;So, I decided that I want to get the sum of all the numbers in my array and get them as a single value. This is where my &lt;em&gt;reduce() method&lt;/em&gt; comes in. The only other way I know of getting this exact result is by using a &lt;em&gt;for loop&lt;/em&gt;, but have you seen the above code? it's shorter, easier and straight forward.&lt;/p&gt;

&lt;p&gt;Let's continue.&lt;/p&gt;

&lt;p&gt;Another thing the above codes have in common is &lt;code&gt;evenNums.reduce()&lt;/code&gt; In this case, the reduce method is being called on the array, which is stored in the variable named &lt;em&gt;evenNums&lt;/em&gt;.  &lt;/p&gt;

&lt;p&gt;This is where it gets different. Es6 uses the arrow function which is literally a syntactic sugar, and you do not have to use a return function. So, in the first example, we have &lt;code&gt;(accumulator, currVal) =&amp;gt; accumulator + currVal&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The reduce method iterates over the values of an array to return a single value. It takes four argument - &lt;em&gt;accumulator, currVal, index and array.&lt;/em&gt; However, the index and array aren't always required. The first two (accumulator and currVal are required and &lt;em&gt;compulsory&lt;/em&gt;). &lt;/p&gt;

&lt;p&gt;The accumulator is a holder for the values. While the currVal, like the name implies holds the current value in the operation (and the operation in this instance is the addition (+) called on the function.&lt;/p&gt;

&lt;p&gt;This is our array &lt;code&gt;[2, 4, 6, 8]&lt;/code&gt; and we want to &lt;em&gt;reduce&lt;/em&gt; it to a single value. And in our function, the 'way' we want it to be reduced is by adding the values together. &lt;/p&gt;

&lt;p&gt;Remember I said, reduce() method works like iteration, so the currVal holds the first value &lt;em&gt;2&lt;/em&gt;, then it sees the operator to be used &lt;em&gt;+&lt;/em&gt; then it iterates (moves to the next value), &lt;em&gt;4&lt;/em&gt;, adds it together and stores the sum (which is &lt;em&gt;6&lt;/em&gt;) in the accumulator. It then takes the value from the accumulator and performs the operation '+' with the next value in the array. And so on till it reaches the last item in the array.&lt;/p&gt;

&lt;p&gt;The function method follows the same convention. You declare your anonymous function, give it arguments, and voila, return what you want with the given arguments. &lt;code&gt;evenNums.reduce( function (accumulator, currVal){&lt;br&gt;
    return accumulator + currVal&lt;br&gt;
})&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Can you guess what the answer is?&lt;/p&gt;

&lt;p&gt;If you did try it and if you didn't, copy out any of the above codes into your chrome developer tools (or any other tool you use), and see if you got it (or what the answer is if you didn't try it).&lt;/p&gt;

&lt;h1&gt;
  
  
  (accumulator, currVal) are not fixed names!
&lt;/h1&gt;

&lt;p&gt;You can use to name your arguments anything. &lt;em&gt;(total, val) (accum, vals)&lt;/em&gt; &lt;em&gt;anything!&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  The operation you can perform are limitless
&lt;/h1&gt;

&lt;p&gt;The beautiful thing about reduce() method is, you can perform any operation you want with it. I have used addition (+), subtraction (-), division (-), multiplication (*), modulo (%), but of course the operations are limitless and you can try any mathematical operation you want.&lt;/p&gt;

&lt;p&gt;Go ahead, open your chrome dev tools (or any other tools), and try writing out a reduce method with a different operator &lt;/p&gt;

&lt;h1&gt;
  
  
  What is reduce() method
&lt;/h1&gt;

&lt;p&gt;Admittedly, this should have come first, but it was going to be a link to a great article that gives all the essay-y educative bit of reduce(), so I decided to leave it till later part.&lt;/p&gt;

&lt;p&gt;For an insightful read on Javascript reduce method, I would suggest you check out this link. [&lt;a href="https://www.educative.io/edpresso/what-is-reduce-in-javascript"&gt;https://www.educative.io/edpresso/what-is-reduce-in-javascript&lt;/a&gt;].&lt;/p&gt;

&lt;h1&gt;
  
  
  Going in-depth into reduce() method
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Totally unrelated: I feel like adding 'method' after 'reduce() is a tautology, since the brackets already mean that it's a method.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Reduce() is a very powerful tool I would suggest you get into and utilize properly. For instance, using the index and array arguments of the reduce method, you could use it as a map and filter for your array. You could return another array, get only values that are divisible by eight, greater than four, or any other 'filterable' operation you can think of.&lt;/p&gt;

&lt;p&gt;An if statement can be used in a reduce method. An array could also be flattened using a reduce method.&lt;/p&gt;

&lt;p&gt;Check out the FreeCodeCamp article, a guide to reduce method to learn much more complex bits of the reduce function. [&lt;a href="https://www.freecodecamp.org/news/reduce-f47a7da511a9/"&gt;https://www.freecodecamp.org/news/reduce-f47a7da511a9/&lt;/a&gt;].&lt;/p&gt;

&lt;h1&gt;
  
  
  Resources
&lt;/h1&gt;

&lt;p&gt;Other resources to check out includes the MDN documentation on reduce() [&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;Bitdegree's basics of applying Javascript Reduce on Array [&lt;a href="https://www.bitdegree.org/learn/javascript-reduce"&gt;https://www.bitdegree.org/learn/javascript-reduce&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;Lastly, finally, Understand the Javascript Reduce Method by Paul Ryan [&lt;a href="https://alligator.io/js/finally-understand-reduce/"&gt;https://alligator.io/js/finally-understand-reduce/&lt;/a&gt;].&lt;/p&gt;

&lt;p&gt;If this article wasn't clear enough, do check out all the resources I have provided. They are brilliant. If you have any more questions, I'd be sure to answer them in the discussion section below. If you would like to correct something, add something (especially a useful resource), do leave a comment in the discussion below.&lt;/p&gt;

&lt;p&gt;Happy coding.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>reduce</category>
      <category>es6</category>
    </item>
  </channel>
</rss>
