<?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: Urooba</title>
    <description>The latest articles on DEV Community by Urooba (@uroobacodes).</description>
    <link>https://dev.to/uroobacodes</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%2F1279205%2F9adff4c8-2bbe-4e83-a848-a251f2c02f0c.png</url>
      <title>DEV Community: Urooba</title>
      <link>https://dev.to/uroobacodes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/uroobacodes"/>
    <language>en</language>
    <item>
      <title>Case Study: Building a Content Operations Framework &amp; Reporting Architecture</title>
      <dc:creator>Urooba</dc:creator>
      <pubDate>Tue, 23 Sep 2025 08:10:27 +0000</pubDate>
      <link>https://dev.to/uroobacodes/case-study-building-a-content-operations-framework-reporting-architecture-31bm</link>
      <guid>https://dev.to/uroobacodes/case-study-building-a-content-operations-framework-reporting-architecture-31bm</guid>
      <description>&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Before my role as Content Manager, the team had:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;No content operations framework, so production wasn’t structured or measurable.&lt;/li&gt;
&lt;li&gt;No reporting architecture and leadership couldn’t see what had been produced or present metrics to investors.&lt;/li&gt;
&lt;li&gt;No granularity and no way to break content down by week, month, year, or category.&lt;/li&gt;
&lt;li&gt;No accountability and the status of the content (proofread, in CMS, published) wasn’t tracked anywhere.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Solution: A Content Operations Framework in Google Sheets
&lt;/h2&gt;

&lt;p&gt;I built a content operations and reporting framework that functioned like a mini relational database:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Modeling (Granularity &amp;amp; Count System)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduced a “count” field, now every article/script was assigned a measurable unit.&lt;/li&gt;
&lt;li&gt;Enabled pivot tables and charts to aggregate content at multiple levels: weekly, monthly, yearly.&lt;/li&gt;
&lt;li&gt;Delivered reporting granularity that didn’t exist before.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;ETL Workflow (Extract, Transform, Load)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Used IMPORTRANGE to extract data from multiple team sheets.&lt;/li&gt;
&lt;li&gt;Used XLOOKUP with a reference table (a data dictionary) to transform raw categories into standardized content types.&lt;/li&gt;
&lt;li&gt;Loaded the clean data into a master content roundup sheet for monthly reporting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This was essentially an ETL pipeline, but fully inside Google Sheets.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interactive Reporting Architecture&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Designed an editorial calendar with data validation (dates) and TEXT function (weekdays).&lt;/li&gt;
&lt;li&gt;Created a weekly reporting dashboard:

&lt;ul&gt;
&lt;li&gt;Dropdown control (Week 1–5).&lt;/li&gt;
&lt;li&gt;Linked bar chart updating counts by content category.&lt;/li&gt;
&lt;li&gt;Real-time visualization of weekly output.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Vertical Ownership: Nutrition 2.0&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Built and managed a dedicated system for the Nutrition vertical:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Article title (hyperlinked to Drive).&lt;/li&gt;
&lt;li&gt;Category.&lt;/li&gt;
&lt;li&gt;Creatives.&lt;/li&gt;
&lt;li&gt;Count.&lt;/li&gt;
&lt;li&gt;Status (proofread, CMS, app).&lt;/li&gt;
&lt;li&gt;Inspiration articles.&lt;/li&gt;
&lt;li&gt;Provided end-to-end visibility into one of the app’s most critical content areas.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Course Design Planning&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Collaborated using Miro boards to plan courses.&lt;/li&gt;
&lt;li&gt;Defined content mix: cards, articles, videos, podcasts.&lt;/li&gt;
&lt;li&gt;Created a framework for multi-format learning pathways.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Impact
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Created the first content operations framework for the company.&lt;/li&gt;
&lt;li&gt;Delivered a reporting architecture that gave leadership real-time insights.&lt;/li&gt;
&lt;li&gt;Brought granularity into production tracking (weekly, monthly, yearly views).&lt;/li&gt;
&lt;li&gt;Eliminated manual duplication via an ETL-style workflow with IMPORTRANGE and XLOOKUP.&lt;/li&gt;
&lt;li&gt;Introduced a data dictionary to standardize categories across the organization.&lt;/li&gt;
&lt;li&gt;Provided investor-ready reporting enabling the owner to present credible, data-backed metrics.&lt;/li&gt;
&lt;li&gt;Professionalized the content process, transforming it from ad hoc to structured, measurable, and scalable.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  🎥 Watch the Demo
&lt;/h2&gt;

&lt;p&gt;Watch the video demo to see the content tracker, editorial calendar, and reporting dashboards in action:&lt;br&gt;
&lt;a href="https://www.youtube.com/watch?v=QDoY2VVA6Mk" rel="noopener noreferrer"&gt;Case Study Demo&lt;/a&gt;&lt;/p&gt;

</description>
      <category>googlecloud</category>
      <category>analytics</category>
      <category>database</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Responsive JavaScript Carousel for API Hourly Data</title>
      <dc:creator>Urooba</dc:creator>
      <pubDate>Mon, 21 Oct 2024 06:27:06 +0000</pubDate>
      <link>https://dev.to/uroobacodes/responsive-javascript-carousel-for-api-hourly-data-55in</link>
      <guid>https://dev.to/uroobacodes/responsive-javascript-carousel-for-api-hourly-data-55in</guid>
      <description>&lt;p&gt;I almost mistook an incomplete solution for a finished one and moved on to work on other parts of my weather app! While working on the carousel that was supposed to show 12 hours of weather, I wanted to add the feature which would help in fetching the next day’s hours in case the current day was finished. However, instead of transitioning to the next day, the carousel kept looping back to the beginning of the current day's hours, and I mistakenly thought the task was complete. Yikes!&lt;/p&gt;

&lt;h2&gt;
  
  
  Initial Challenges
&lt;/h2&gt;

&lt;p&gt;I thought about two ‘for loops’ but I don’t think that ‘j’ printing all its elements for the length of the entire ‘i’ was correct. I found a lot of blogs online about the use of modulus operator for "circular array" But I did not know how that would help my case. I needed to loop through the current day's hours and then switch to the next day once the hours reset to zero. A lot was happening and I needed to make it more concise and place everything in one function. Tough! &lt;/p&gt;

&lt;h2&gt;
  
  
  Recognizing Incomplete Solutions and Mistakes
&lt;/h2&gt;

&lt;p&gt;I found something really &lt;a href="https://blog.logrocket.com/mastering-modulo-operator-javascript/" rel="noopener noreferrer"&gt;cool&lt;/a&gt; online though, it may solve a big problem for me. It helped me understand how modulus operator works for circular arrays. Here is the example on the website:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const daysOfWeek = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];
// Function to cycle through the days of the week
function cycleDays(index) {
  return daysOfWeek[index % daysOfWeek.length];
}
// Let's cycle through the days:
for (let i = 0; i &amp;lt; 10; i++) {
  console.log(`Day ${i + 1}: ${cycleDays(i)}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The result is like:&lt;/strong&gt;&lt;br&gt;
Day 1: Monday&lt;br&gt;
Day 2: Tuesday&lt;br&gt;
...&lt;br&gt;&lt;br&gt;
What I wanted was, instead of going back to the &lt;strong&gt;daysOfWeek&lt;/strong&gt; array, and start from &lt;strong&gt;‘Monday’&lt;/strong&gt;, it should go to a completely different array. So, I took the code to the code editor and changed it a bit. First, I made a variable called &lt;strong&gt;‘currentIndex’&lt;/strong&gt; and stored the modulus operation in it. Then I logged it to the console. It reset after 6 and became zero again. &lt;/p&gt;

&lt;p&gt;Though, I was logging the wrong variable to the console. Because, if I wrote the if condition like this: &lt;strong&gt;if(currentIndex === 0)&lt;/strong&gt;, it would actually move toward a new array right at the beginning of the loop. So, now I logged the "index" instead, and finally I found the answer! In order to test the new code, I made a new array for &lt;strong&gt;‘months’&lt;/strong&gt; and then tried to make the switch. But I made another mistake—let me show you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const daysOfWeek = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];
const months = [
  'Jan',
  'Feb',
  'March'
];
// Function to cycle through the days of the week
function cycleDays(index) {
  let currentIndex = index % daysOfWeek.length
  console.log(index)
 if(index === 7){
   return months[currentIndex]
 } else {
     return daysOfWeek[currentIndex];
 }
}
// Let's cycle through the days:
for (let i = 0; i &amp;lt; 10; i++) {
  console.log(`Day ${i + 1}: ${cycleDays(i)}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After logging "Jan", it switched back to the original array. The mistake was strict equality check, I should have used &lt;strong&gt;‘greater than or equal to’&lt;/strong&gt; instead. When I plugged that in, it successfully switched to the new array!&lt;/p&gt;

&lt;p&gt;Now, I wanted the loop to start from the current hour and continue without stopping, with a marker in place to switch between the arrays. That marker will be the modulus operator instead of the length of the array. I could also use the length of the array, which in this case is 9 (and for my API data, 24), but I’m sticking to the hard-coded value of 9 for now.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;currentIndex = (currentIndex + 1) % 9&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This line allows me to switch from day one to day two during the loop without stopping it. Here's another trial (I updated the arrays to resemble API results):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dayOne = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const dayTwo = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let hours = dayOne;
let currentHour = 5;
function cycleDays(currentHour) {
  let currentIndex = currentHour
  for (let i = 0; i &amp;lt; 10; i++) {
    console.log(`index is ${currentIndex} and dayOne is ${hours[currentIndex]}`)
    if(currentIndex === 0){
      hours = dayTwo
    console.log(`index is ${currentIndex} and dayTwo is ${hours[currentIndex]}`)
    } 
  currentIndex = (currentIndex + 1) % 9

} 
}
cycleDays(currentHour)

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

&lt;/div&gt;



&lt;p&gt;Notice something interesting in the results: &lt;/p&gt;

&lt;p&gt;index is 5 and dayOne is six and i is 0&lt;br&gt;
index is 6 and dayOne is seven and i is 1&lt;br&gt;
index is 7 and dayOne is eight and i is 2&lt;br&gt;
index is 8 and dayOne is nine and i is 3&lt;br&gt;
index is 9 and dayOne is ten and i is 4&lt;br&gt;
index is 0 and dayOne is one and i is 5&lt;br&gt;
&lt;strong&gt;index is 0 and dayTwo is 11&lt;/strong&gt;&lt;br&gt;
index is 1 and dayOne is 12 and i is 6&lt;br&gt;
index is 2 and dayOne is 13 and i is 7&lt;br&gt;
index is 3 and dayOne is 14 and i is 8&lt;br&gt;
index is 4 and dayOne is 15 and i is 9&lt;/p&gt;

&lt;p&gt;The issue here is that even after switching hours from dayOne to dayTwo, the logs still refer to dayOne in the log statements. This happens because the logging statement is hardcoded to say "dayOne" even though the array has switched to dayTwo.&lt;/p&gt;

&lt;p&gt;To fix this, we can set another marker for the day and make it switch at the same time as we switch the arrays. I am going to switch the dayOne and dayTwo to 'monday' and 'tuesday' respectively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const monday = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const tuesday = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let hours = monday;
let currentHour = 5;
let day = 'monday';

function cycleDays(currentHour) {
  let currentIndex = currentHour;
  for (let i = 0; i &amp;lt; 10; i++) {
    console.log(`index is ${currentIndex} and ${day} is ${hours[currentIndex]} and i is ${i}`);

    if (currentIndex === 0) {
      hours = tuesday; 
      day = 'tuesday'; 
      console.log(`index is ${currentIndex} and ${day} is ${hours[currentIndex]}`);
    }
    currentIndex = (currentIndex + 1) % 10;
  }
}

cycleDays(currentHour);

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

&lt;/div&gt;



&lt;p&gt;My code is almost there. The two significant changes that made this code work were tracking the day and placing the modulus operation inside the for loop. &lt;/p&gt;

&lt;p&gt;Finally, I can construct my code for the 3-day data I am retrieving from the api, here is the refined version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createHours(days){
        if (!days || days.length === 0) {
            console.error("Days array is undefined or empty");
            return; // Prevent further execution if data is missing
        }
        const btnNext = document.querySelector('.next');
        const btnPrev = document.querySelector('.previous');
        const hourContainer = document.querySelector('.tfour_hours');
        const currentHour = new Date().getHours()
        function getHoursForDay(index) {
         return days[index].hour; 
        }
        let dayIndex = 0;
        let hours = getHoursForDay(dayIndex);
        let index = currentHour;
        let displayHours = [];
        for (let i = 0; i &amp;lt; 12; i++) {
            // console.log(hours)
            // console.log(`index: ${index}`)
            let hourData = hours[index];
            let hourNum = index &amp;lt; 10 ? `0${index}` : index;

            if (index === 0) {
                displayHours.push(`
                    &amp;lt;div class="hour-${i} child"&amp;gt;
                        &amp;lt;p class="next-day"&amp;gt;Next Day&amp;lt;/p&amp;gt;
                        &amp;lt;p class="next-hour-num"&amp;gt;${hourNum}&amp;lt;/p&amp;gt;
                        &amp;lt;img class="icon" src="https:${hourData.condition.icon}" alt="icon"&amp;gt;
                        &amp;lt;p class="temp"&amp;gt;${hourData.temp_c}°C&amp;lt;/p&amp;gt;
                    &amp;lt;/div&amp;gt;
                `);
            } else {
                displayHours.push(`
                    &amp;lt;div class="hour-${i} child"&amp;gt;
                        &amp;lt;p class="hour-num"&amp;gt;${hourNum}&amp;lt;/p&amp;gt;
                        &amp;lt;img class="icon" src="https:${hourData.condition.icon}" alt="icon"&amp;gt;
                        &amp;lt;p class="temp"&amp;gt;${hourData.temp_c}°C&amp;lt;/p&amp;gt;
                    &amp;lt;/div&amp;gt;
                `);
            }
                    index = (index + 1) % 24;
            if(index === 0 &amp;amp;&amp;amp; dayIndex === 0){
                dayIndex = 1;
                hours = getHoursForDay(dayIndex)
            }
        } //for loop
            displayHours = displayHours.join('');
        hourContainer.innerHTML = displayHours;
…
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating Dynamic HTML Elements
&lt;/h2&gt;

&lt;p&gt;Let’s talk about generating the 12 divs. I couldn’t picture how to get the buttons on either side of the parent div while the 12 hours just float in between them. If I were to generate the 12 divs in the same parent as the buttons, then the button elements would need a different justification setting than the 12 divs. &lt;/p&gt;

&lt;p&gt;It only made sense to let them have their own container. It took me a while to figure this out—I actually had to sleep on it. Then next day, I typed &lt;strong&gt;.btn-container&lt;/strong&gt; and hit tab and from there, everything clicked. I had seen every grouped item and their own containers inside parent containers in John Smilga's tutorials, I did not know why such grouping would be necessary until I started to design the 24-hour container. It was a real 'gotcha moment'.&lt;/p&gt;

&lt;p&gt;Now came another problem that lingered for days. The slider that I designed in the tutorials was not as challenging as these divs. In the tutorials, there was a simple translate value, but right now I have quite a few issues. On smaller screens, the divs were sticking together and starting to look like spaghetti. &lt;/p&gt;

&lt;p&gt;And, when I used a simple translateX property, meaning when I 'guessed’ the pixels, there was a lot of space left after the divs had completely translated to the left. It meant they were translating more than their combined width. I needed to find a proper value to ensure the divs stopped exactly at the end without leaving that extra space. After searching for a long time, I came across a &lt;a href="https://dev.to/ranewallin/this-simple-math-hack-lets-you-create-an-image-carousel-without-any-if-statements-5chj"&gt;blog&lt;/a&gt; that offered various solutions.&lt;/p&gt;

&lt;p&gt;There were a lot of solutions. A few of them were using modulo operator, which reminded me of the circular array logic I had applied when switching days in the ‘for loop’. There were a lot comments here that used &lt;strong&gt;Math.min&lt;/strong&gt; and &lt;strong&gt;Math.max&lt;/strong&gt;. Which basically would make the container translate until the end of its length was reached. Excellent! So no more white space?  Not so fast...&lt;/p&gt;

&lt;p&gt;One thing that differed from these examples was that my container would initially display 3 or 4 divs. So, when the offset is 0, there is already a certain amount of length in the parent container. &lt;/p&gt;

&lt;p&gt;They were showing the image by adding the number 1. So, their carousel would slide 1 image forward according to the index number of the images in the array. For example, if there are 10 images in a container, and we add one to the &lt;strong&gt;currentImage&lt;/strong&gt; variable, the value calculated by &lt;strong&gt;Math.min&lt;/strong&gt; will be '1'. Then, when we add another '1', the current image will be 2 and the value will be 2 by &lt;strong&gt;Math.min&lt;/strong&gt; because 2 mod 10 is 2. This particular example would change the game of the slider that I am trying to make. This was the code that caught my eye:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const imageData = [ 'image1.png', 'img2.png', 'img3.png', ... ];
let currentImage = 0;
____
const handleImageChange = (imageShift) =&amp;gt; {
  currentImage = Math.max(
    0,
    Math.min(
      imageData.length - 1,
      (currentImage + imageShift) % imageData.length
    )
  );
}
____
const firstImage = () =&amp;gt; handleImageChange(-imageData.length);
const prevImage = () =&amp;gt; handleImageChange(-1);
const nextImage = () =&amp;gt; handleImageChange(1);
const lastImage = () =&amp;gt; handleImageChange(imageData.length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The brilliance behind Richard Kichenama's solution, found in the comments, lies in the use of Math.max to ensure the value doesn’t drop below 0 and Math.min to calculate the translation value until it reaches the maximum length of the image array.&lt;/p&gt;

&lt;p&gt;Now, how was I to solve the problem of the white space? I had to consider the margins of all of the child divs and add them together to get the entire length of the children divs. Then, the slider should stop moving once the last child is reached. This means the total width is the sum of all the children's widths plus their margins.&lt;/p&gt;

&lt;p&gt;However, I ran into another issue: some of the divs were already displayed in the container, which left me stuck again. Luckily, a friend of mine came to the rescue. After discussing the problem with them, here's what I understood:&lt;/p&gt;

&lt;p&gt;I could not consider the entire length of the children divs. There was almost as much of white space left as the container length. The solution was to subtract the parent container's length from the total length of the children (including margins). This adjustment helped resolve the white space issue—phew!&lt;/p&gt;

&lt;p&gt;Some of the code examples had a variable that was kind of like a ‘counter’. It acted as a ‘counter’ for translate property. When this variable increased, the translate property increased and so on. I separated the &lt;strong&gt;Math.min&lt;/strong&gt; and &lt;strong&gt;Math.max&lt;/strong&gt; properties for the next and previous buttons. It was more helpful and easier that way. &lt;/p&gt;

&lt;p&gt;In the examples I referenced, the code was using the length of the array to determine the slide distance, but, as per my previous discussion with my friend, I needed to consider the white space so I have to subtract the length of the container. This way, I ensured that my divs could only move by a specific amount, avoiding the extra space at the end.&lt;/p&gt;

&lt;p&gt;Also, thanks to john smilga's tutorials, I learned how to get the width, height, top properties of items. It was a struggle to apply the right one, it was also a struggle to find out that some of the values are strings and needed to be turned into numbers. I found that easily on google and got introduced to &lt;strong&gt;‘parseFloat’&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I also came across another helpful &lt;a href="https://pieces.app/blog/introduction-to-building-responsive-ui-with-css-calc" rel="noopener noreferrer"&gt;resource &lt;/a&gt;that taught me how to display only three divs for large screens and two divs for small screens. The trick was to divide 100% of the container’s width by 3 (or 2 for small screens) and subtract the margins. This allowed for equally sized divs that fit perfectly within the container (so clever!). Finally, to check out the final function, please visit my &lt;a href="https://github.com/uroobaCodes" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. &lt;a href="https://github.com/uroobaCodes/12HourForecast" rel="noopener noreferrer"&gt;Here &lt;/a&gt;is the link to my repository. &lt;/p&gt;

&lt;p&gt;The window event listener for resizing was crucial in fixing the alignment issues in my container. It addressed the "Flash of Unstyled Content" (FOUC) problem by resetting the offset on resize. I have to thank my friend for helping me understand how to calculate maxOffset—that was a real game changer.&lt;/p&gt;

&lt;p&gt;Lastly, a shout-out to all experienced developers: every word you share helps someone new to the field. So, keep posting the information from your end, as we are waiting on the other side eager to learn. Thank you! &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Responsive JavaScript Carousel for API Hourly Data</title>
      <dc:creator>Urooba</dc:creator>
      <pubDate>Mon, 21 Oct 2024 06:27:06 +0000</pubDate>
      <link>https://dev.to/uroobacodes/responsive-javascript-carousel-for-api-hourly-data-309m</link>
      <guid>https://dev.to/uroobacodes/responsive-javascript-carousel-for-api-hourly-data-309m</guid>
      <description>&lt;p&gt;I almost mistook an incomplete solution for a finished one and moved on to work on other parts of my weather app! While working on the carousel that was supposed to show 12 hours of weather, I wanted to add the feature which would help in fetching the next day’s hours in case the current day was finished. However, instead of transitioning to the next day, the carousel kept looping back to the beginning of the current day's hours, and I mistakenly thought the task was complete. Yikes!&lt;/p&gt;

&lt;h2&gt;
  
  
  Initial Challenges
&lt;/h2&gt;

&lt;p&gt;I thought about two ‘for loops’ but I don’t think that ‘j’ printing all its elements for the length of the entire ‘i’ was correct. I found a lot of blogs online about the use of modulus operator for "circular array" But I did not know how that would help my case. I needed to loop through the current day's hours and then switch to the next day once the hours reset to zero. A lot was happening and I needed to make it more concise and place everything in one function. Tough! &lt;/p&gt;

&lt;h2&gt;
  
  
  Recognizing Incomplete Solutions and Mistakes
&lt;/h2&gt;

&lt;p&gt;I found something really &lt;a href="https://blog.logrocket.com/mastering-modulo-operator-javascript/" rel="noopener noreferrer"&gt;cool&lt;/a&gt; online though, it may solve a big problem for me. It helped me understand how modulus operator works for circular arrays. Here is the example on the website:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const daysOfWeek = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];
// Function to cycle through the days of the week
function cycleDays(index) {
  return daysOfWeek[index % daysOfWeek.length];
}
// Let's cycle through the days:
for (let i = 0; i &amp;lt; 10; i++) {
  console.log(`Day ${i + 1}: ${cycleDays(i)}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The result is like:&lt;/strong&gt;&lt;br&gt;
Day 1: Monday&lt;br&gt;
Day 2: Tuesday&lt;br&gt;
...&lt;br&gt;&lt;br&gt;
What I wanted was, instead of going back to the &lt;strong&gt;daysOfWeek&lt;/strong&gt; array, and start from &lt;strong&gt;‘Monday’&lt;/strong&gt;, it should go to a completely different array. So, I took the code to the code editor and changed it a bit. First, I made a variable called &lt;strong&gt;‘currentIndex’&lt;/strong&gt; and stored the modulus operation in it. Then I logged it to the console. It reset after 6 and became zero again. &lt;/p&gt;

&lt;p&gt;Though, I was logging the wrong variable to the console. Because, if I wrote the if condition like this: &lt;strong&gt;if(currentIndex === 0)&lt;/strong&gt;, it would actually move toward a new array right at the beginning of the loop. So, now I logged the "index" instead, and finally I found the answer! In order to test the new code, I made a new array for &lt;strong&gt;‘months’&lt;/strong&gt; and then tried to make the switch. But I made another mistake—let me show you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const daysOfWeek = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];
const months = [
  'Jan',
  'Feb',
  'March'
];
// Function to cycle through the days of the week
function cycleDays(index) {
  let currentIndex = index % daysOfWeek.length
  console.log(index)
 if(index === 7){
   return months[currentIndex]
 } else {
     return daysOfWeek[currentIndex];
 }
}
// Let's cycle through the days:
for (let i = 0; i &amp;lt; 10; i++) {
  console.log(`Day ${i + 1}: ${cycleDays(i)}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After logging "Jan", it switched back to the original array. The mistake was strict equality check, I should have used &lt;strong&gt;‘greater than or equal to’&lt;/strong&gt; instead. When I plugged that in, it successfully switched to the new array!&lt;/p&gt;

&lt;p&gt;Now, I wanted the loop to start from the current hour and continue without stopping, with a marker in place to switch between the arrays. That marker will be the modulus operator instead of the length of the array. I could also use the length of the array, which in this case is 24, but I’m sticking to the hard-coded value of 24 for now.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;currentIndex = (currentIndex + 1) % 9&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This line allows me to switch from day one to day two during the loop without stopping it. Here's another trial (I updated the arrays to resemble API results):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dayOne = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const dayTwo = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let hours = dayOne;
let currentHour = 5;
function cycleDays(currentHour) {
  let currentIndex = currentHour
  for (let i = 0; i &amp;lt; 10; i++) {
    console.log(`index is ${currentIndex} and dayOne is ${hours[currentIndex]}`)
    if(currentIndex === 0){
      hours = dayTwo
    console.log(`index is ${currentIndex} and dayTwo is ${hours[currentIndex]}`)
    } 
  currentIndex = (currentIndex + 1) % 9

} 
}
cycleDays(currentHour)

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

&lt;/div&gt;



&lt;p&gt;Notice something interesting in the results: &lt;/p&gt;

&lt;p&gt;index is 5 and monday is six and i is 0&lt;br&gt;
index is 6 and monday is seven and i is 1&lt;br&gt;
index is 7 and monday is eight and i is 2&lt;br&gt;
index is 8 and monday is nine and i is 3&lt;br&gt;
index is 9 and monday is ten and i is 4&lt;br&gt;
index is 0 and monday is one and i is 5&lt;br&gt;
&lt;strong&gt;index is 0 and tuesday is 11&lt;/strong&gt;&lt;br&gt;
index is 1 and monday is 12 and i is 6&lt;br&gt;
index is 2 and monday is 13 and i is 7&lt;br&gt;
index is 3 and monday is 14 and i is 8&lt;br&gt;
index is 4 and monday is ¬15 and i is 9&lt;/p&gt;

&lt;p&gt;The issue here is that the loop runs once from the start, and when it reaches the condition &lt;strong&gt;(if(currentIndex === 0))&lt;/strong&gt;, it switches the array. However, when currentIndex = 0 (i.e., 10 % 10 = 0), the &lt;strong&gt;hours[currentIndex]&lt;/strong&gt; is accessed before the if condition is executed. That’s why you see values from dayOne (like "one") even after the switch.&lt;/p&gt;

&lt;p&gt;To fix this, the if condition needs to be checked right after &lt;strong&gt;currentIndex&lt;/strong&gt; becomes 0, so that the array switch happens before logging:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;console.log(&lt;code&gt;index is ${currentIndex} and monday is ${hours[currentIndex]} and i is ${i}&lt;/code&gt;)...&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By changing the position of the condition, it can be ensured that the switch occurs at the correct time without first accessing the wrong array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const monday = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const tuesday = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let hours = monday;
let currentHour = 5;
function cycleDays(currentHour) {
  let currentIndex = currentHour
  for (let i = 0; i &amp;lt; 10; i++) {
    console.log(`index is ${currentIndex} and monday is ${hours[currentIndex]} and i is ${i}`)
    if(currentIndex === 0){
      hours = tuesday
    console.log(`index is ${currentIndex} and tuesday is ${hours[currentIndex]}`)
    } 
  currentIndex = (currentIndex + 1) % 10
} //for 
}
cycleDays(currentHour)

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

&lt;/div&gt;



&lt;p&gt;My code is almost there. Here, the only mistake I am making is logging &lt;strong&gt;‘Monday’&lt;/strong&gt; instead of &lt;strong&gt;‘Tuesday’&lt;/strong&gt;. The values are from the &lt;strong&gt;‘Tuesday’&lt;/strong&gt; array though, but it keeps saying &lt;strong&gt;‘Monday’&lt;/strong&gt; because of the wrong way of writing the console.log statement. I guess, It is quite hard to put two and two together and picture logging VS actually putting in values into html elements. Here is a bit of improvement using ternary operator (yes, I switched the elements of the array, again!):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const monday = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const tuesday = ['apple', 'orange', 'banana', 'pineapple', 'grapes', 'cherries', 'strawberries', 'mangoes', 'blueberries', 'pears'];
let hours = monday;
let currentHour = 9;
function cycleDays(currentHour) {
  let currentIndex = currentHour
  for (let i = 0; i &amp;lt; 14; i++) {
  hours === monday ? console.log(`day: monday, elements: ${hours[currentIndex]}`) : console.log(`day: tuesday, elements: ${hours[currentIndex]}`)
  currentIndex = (currentIndex + 1) % 10
   if(currentIndex === 0 &amp;amp;&amp;amp; hours === monday){
      hours = tuesday
    } 
} //for 
}
cycleDays(currentHour);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, I can construct my code for the 3-day data I am retrieving from the api, here is the refined version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createHours(days){
        if (!days || days.length === 0) {
            console.error("Days array is undefined or empty");
            return; // Prevent further execution if data is missing
        }
        const btnNext = document.querySelector('.next');
        const btnPrev = document.querySelector('.previous');
        const hourContainer = document.querySelector('.tfour_hours');
        const currentHour = new Date().getHours()
        function getHoursForDay(index) {
         return days[index].hour; 
        }
        let dayIndex = 0;
        let hours = getHoursForDay(dayIndex);
        let index = currentHour;
        let displayHours = [];
        for (let i = 0; i &amp;lt; 12; i++) {
            // console.log(hours)
            // console.log(`index: ${index}`)
            let hourData = hours[index];
            let hourNum = index &amp;lt; 10 ? `0${index}` : index;

            if (index === 0) {
                displayHours.push(`
                    &amp;lt;div class="hour-${i} child"&amp;gt;
                        &amp;lt;p class="next-day"&amp;gt;Next Day&amp;lt;/p&amp;gt;
                        &amp;lt;p class="next-hour-num"&amp;gt;${hourNum}&amp;lt;/p&amp;gt;
                        &amp;lt;img class="icon" src="https:${hourData.condition.icon}" alt="icon"&amp;gt;
                        &amp;lt;p class="temp"&amp;gt;${hourData.temp_c}°C&amp;lt;/p&amp;gt;
                    &amp;lt;/div&amp;gt;
                `);
            } else {
                displayHours.push(`
                    &amp;lt;div class="hour-${i} child"&amp;gt;
                        &amp;lt;p class="hour-num"&amp;gt;${hourNum}&amp;lt;/p&amp;gt;
                        &amp;lt;img class="icon" src="https:${hourData.condition.icon}" alt="icon"&amp;gt;
                        &amp;lt;p class="temp"&amp;gt;${hourData.temp_c}°C&amp;lt;/p&amp;gt;
                    &amp;lt;/div&amp;gt;
                `);
            }
                    index = (index + 1) % 24;
            if(index === 0 &amp;amp;&amp;amp; dayIndex === 0){
                dayIndex = 1;
                hours = getHoursForDay(dayIndex)
            }
        } //for loop
            displayHours = displayHours.join('');
        hourContainer.innerHTML = displayHours;
…
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating Dynamic HTML Elements
&lt;/h2&gt;

&lt;p&gt;Let’s talk about generating the 12 divs. I couldn’t picture how to get the buttons on either side of the parent div while the 12 hours just float in between them. If I were to generate the 12 divs in the same parent as the buttons, then the button elements would need a different justification setting than the 12 divs. &lt;/p&gt;

&lt;p&gt;It only made sense to let them have their own container. It took me a while to figure this out—I actually had to sleep on it. Then next day, I typed &lt;strong&gt;.btn-container&lt;/strong&gt; and hit tab and from there, everything clicked. I had seen every grouped item and their own containers inside parent containers in John Smilga's tutorials, I did not know why such grouping would be necessary until I started to design the 24-hour container. It was a real 'gotcha moment'.&lt;/p&gt;

&lt;p&gt;Now came another problem that lingered for days. The slider that I designed in the tutorials was not as challenging as these divs. In the tutorials, there was a simple translate value, but right now I have quite a few issues. On smaller screens, the divs were sticking together and starting to look like spaghetti. &lt;/p&gt;

&lt;p&gt;And, when I used a simple translateX property, meaning when I 'guessed’ the pixels, there was a lot of space left after the divs had completely translated to the left. It meant they were translating more than their combined width. I needed to find a proper value to ensure the divs stopped exactly at the end without leaving that extra space. After searching for a long time, I came across a &lt;a href="https://dev.to/ranewallin/this-simple-math-hack-lets-you-create-an-image-carousel-without-any-if-statements-5chj"&gt;blog&lt;/a&gt; that offered various solutions.&lt;/p&gt;

&lt;p&gt;There were a lot of solutions. A few of them were using modulo operator, which reminded me of the circular array logic I had applied when switching days in the ‘for loop’. There were a lot comments here that used &lt;strong&gt;Math.min&lt;/strong&gt; and &lt;strong&gt;Math.max&lt;/strong&gt;. Which basically would make the container translate until the end of its length was reached. Excellent! So no more white space?  Not so fast...&lt;/p&gt;

&lt;p&gt;One thing that differed from these examples was that my container would initially display 3 or 4 divs. So, when the offset is 0, there is already a certain amount of length in the parent container. &lt;/p&gt;

&lt;p&gt;They were showing the image by adding the number 1. So, their carousel would slide 1 image forward according to the index number of the images in the array. For example, if there are 10 images in a container, and we add one to the &lt;strong&gt;currentImage&lt;/strong&gt; variable, the value calculated by &lt;strong&gt;Math.min&lt;/strong&gt; will be '1'. Then, when we add another '1', the current image will be 2 and the value will be 2 by &lt;strong&gt;Math.min&lt;/strong&gt; because 2 mod 10 is 2. This particular example would change the game of the slider that I am trying to make. This was the code that caught my eye:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const imageData = [ 'image1.png', 'img2.png', 'img3.png', ... ];
let currentImage = 0;
____
const handleImageChange = (imageShift) =&amp;gt; {
  currentImage = Math.max(
    0,
    Math.min(
      imageData.length - 1,
      (currentImage + imageShift) % imageData.length
    )
  );
}
____
const firstImage = () =&amp;gt; handleImageChange(-imageData.length);
const prevImage = () =&amp;gt; handleImageChange(-1);
const nextImage = () =&amp;gt; handleImageChange(1);
const lastImage = () =&amp;gt; handleImageChange(imageData.length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The brilliance behind Richard Kichenama's solution, found in the comments, lies in the use of Math.max to ensure the value doesn’t drop below 0 and Math.min to calculate the translation value until it reaches the maximum length of the image array.&lt;/p&gt;

&lt;p&gt;Now, how was I to solve the problem of the white space? I had to consider the margins of all of the child divs and add them together to get the entire length of the children divs. Then, the slider should stop moving once the last child is reached. This means the total width is the sum of all the children's widths plus their margins.&lt;/p&gt;

&lt;p&gt;However, I ran into another issue: some of the divs were already displayed in the container, which left me stuck again. Luckily, a friend of mine came to the rescue. After discussing the problem with them, here's what I understood:&lt;/p&gt;

&lt;p&gt;I could not consider the entire length of the children divs. There was almost as much of white space left as the container length. The solution was to subtract the parent container's length from the total length of the children (including margins). This adjustment helped resolve the white space issue—phew!&lt;/p&gt;

&lt;p&gt;Some of the code examples had a variable that was kind of like a ‘counter’. It acted as a ‘counter’ for translate property. When this variable increased, the translate property increased and so on. I separated the &lt;strong&gt;Math.min&lt;/strong&gt; and &lt;strong&gt;Math.max&lt;/strong&gt; properties for the next and previous buttons. It was more helpful and easier that way. &lt;/p&gt;

&lt;p&gt;In the examples I referenced, the code was using the length of the array to determine the slide distance, but, as per my previous discussion with my friend, I needed to consider the white space so I have to subtract the length of the container. This way, I ensured that my divs could only move by a specific amount, avoiding the extra space at the end.&lt;/p&gt;

&lt;p&gt;Also, thanks to john smilga's tutorials, I learned how to get the width, height, top properties of items. It was a struggle to apply the right one, it was also a struggle to find out that some of the values are strings and needed to be turned into numbers. I found that easily on google and got introduced to &lt;strong&gt;‘parseFloat’&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I also came across another helpful &lt;a href="https://pieces.app/blog/introduction-to-building-responsive-ui-with-css-calc" rel="noopener noreferrer"&gt;resource &lt;/a&gt;that taught me how to display only three divs for large screens and two divs for small screens. The trick was to divide 100% of the container’s width by 3 (or 2 for small screens) and subtract the margins. This allowed for equally sized divs that fit perfectly within the container (so clever!). Finally, to check out the final function, please visit my &lt;a href="https://github.com/uroobaCodes" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. &lt;a href="https://github.com/uroobaCodes/12HourForecast" rel="noopener noreferrer"&gt;Here &lt;/a&gt;is the link to my repository. &lt;/p&gt;

&lt;p&gt;The window event listener for resizing was crucial in fixing the alignment issues in my container. It addressed the "Flash of Unstyled Content" (FOUC) problem by resetting the offset on resize. I have to thank my friend for helping me understand how to calculate maxOffset—that was a real game changer.&lt;/p&gt;

&lt;p&gt;Lastly, a shout-out to all experienced developers: every word you share helps someone new to the field. So, keep posting the information from your end, as we are waiting on the other side eager to learn. Thank you! &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Average with JavaScript</title>
      <dc:creator>Urooba</dc:creator>
      <pubDate>Mon, 12 Feb 2024 17:21:44 +0000</pubDate>
      <link>https://dev.to/uroobacodes/average-with-javascript-4e81</link>
      <guid>https://dev.to/uroobacodes/average-with-javascript-4e81</guid>
      <description>&lt;p&gt;JavaScript 'objects' are simply containers of information. If we examine our LinkedIn profiles, we would find objects of ourselves staring back at us. I can transform my profile into an object and here is what it will look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fau50c36a9d0iy4u3j3iq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fau50c36a9d0iy4u3j3iq.png" alt="Image description" width="391" height="183"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If I were to categorize different aspects of my life, I would need a few objects to paint the complete picture. I can then place all of those objects inside an Array. An Array in JavaScript is also an object too that stores a collection of multiple items. Think of an ‘array object’ as food storage container with a name on it, containing few more containers inside. If I use the example of my LinkedIn profile, I can place my personal information in one object and LinkedIn profile information in another. Then I can place all of that data in an Array with a name:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fz3xl47eqaup3sbczerid.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fz3xl47eqaup3sbczerid.png" alt="Image description" width="528" height="118"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is another example of an Array called ‘games’:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F2edyutwga2uixjsnpbq6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F2edyutwga2uixjsnpbq6.png" alt="Image description" width="424" height="372"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Finding Average:
&lt;/h2&gt;

&lt;p&gt;In the example above, we have a compilation of home team’s scores as well as opponent’s scores. In JavaScript, we can perform interesting mathematical operations that can manipulate numerical data, calculate complex equations, and enhance the overall functionality of our programs. We can use powerful tools to manipulate arrays and perform specific math operations to get the desired result. While I was learning about this, I came across the .forEach() iterator. ‘Iterators’ are tools that loop over an array of elements and inside their code blocks – because iterators are also functions – we can perform any kind of operation we desire.&lt;/p&gt;

&lt;p&gt;In the example of ‘games’ array, I was learning to find the average of home team’s scores. To reach the average using .forEach() iterator, we first need a ‘starting point’. I am going to use a variable to set my starting point at zero:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fji74o0cogu5fym75qi8d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fji74o0cogu5fym75qi8d.png" alt="Image description" width="714" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the code example above, I appended the .forEach() iterator with the games array to iterate or loop through its elements. Since we are only concerned with home team’s points, that’s what my ‘param’ or ‘parameter’ will add to the total score. To achieve that, I appended the ‘teamPoints’ to my function’s parameter.&lt;/p&gt;

&lt;p&gt;To find the average after the .forEach() loop stops iterating, we need to divide the totalScore variable by the length of the 'games' array as per the formula for finding average of a set which is:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Flis7qd84bh5mas0zxqu7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Flis7qd84bh5mas0zxqu7.png" alt="Image description" width="549" height="138"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;where n is the total number of items in a set.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fh3c3iv2mi8ri8qp0yeul.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fh3c3iv2mi8ri8qp0yeul.png" alt="Image description" width="501" height="49"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  .reduce()
&lt;/h2&gt;

&lt;p&gt;We can even make this simpler using a very powerful tool called the .reduce() method. With the help of this method, we can perform all of the calculations in one function and also avoid using an external variable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F97au4fubamuqkqwtnxsi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F97au4fubamuqkqwtnxsi.png" alt="Image description" width="800" height="289"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.reduce()&lt;/strong&gt; has “reduced” the scores to one value, from which we can extract the average easily. The .reduce() method takes a callback function with four parameters, I have left out the last one, which is ‘array’. If we want to see what the ‘index’ parameter does, we can simple print the index to the console in the iterator’s code block:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fuyxg4a6gbmc4pqkdhx1d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fuyxg4a6gbmc4pqkdhx1d.png" alt="Image description" width="800" height="49"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We need to find the average after the loop ends and reaches the finish line, otherwise it won’t return the correct result. To find the average, we need to check if the ‘index’ has reached its end. If you print to the console all of the index numbers, the results will show:&lt;/p&gt;

&lt;p&gt;0&lt;br&gt;
1&lt;br&gt;
2&lt;/p&gt;

&lt;p&gt;And if we printed &lt;strong&gt;games.length&lt;/strong&gt; to the console, the number will show 3. Which is why we want the math operation to work after the loop ends. The loop will end when index is equal to the length of the array minus 1, which will yield 2, since the end of the index is 2.&lt;/p&gt;

&lt;p&gt;Just like the &lt;strong&gt;startingPoint&lt;/strong&gt; variable for the &lt;strong&gt;.forEach()&lt;/strong&gt; loop, we set the &lt;strong&gt;accumulator&lt;/strong&gt; to 0, we can test the &lt;strong&gt;accumulator’s&lt;/strong&gt; value by giving it another number than 0 and it will add that number to the reduction. So it acts like the &lt;strong&gt;startingPoint&lt;/strong&gt; variable for the &lt;strong&gt;.forEach()&lt;/strong&gt; loop. In case of operations like multiplication, the 0 initial value will multiply the numbers with 0 and return 0 as a result, which may not be desirable and cause unexpected errors. We also need to return the &lt;strong&gt;accumulator&lt;/strong&gt; for every loop, so it has something to start from, otherwise for the second iteration, it will be undefined. If we don’t specify an initial value for the &lt;strong&gt;accumulator&lt;/strong&gt;, the reduce function will take the first element of the array as the &lt;strong&gt;accumulator&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I wanted to check whether my loop was working correctly, which is why I only set the scores to the number divisible by 3, since we have 3 elements(objects) in our array. In case the average is a floating point value, we can always use Math.floor() to get a whole number. I can simple wrap the ‘result’ variable like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = Math.floor(result/games.length)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;.reduce()&lt;/strong&gt; high-order function will take a callback function and return a single value. &lt;strong&gt;.reduce()&lt;/strong&gt; is a very powerful tool and it has plenty of use cases. It can also be used to group values or remove duplicates and it is all thanks to the &lt;strong&gt;accumulator&lt;/strong&gt;. If you have used &lt;strong&gt;.reduce()&lt;/strong&gt; for you projects, share it with me. Thank you for reading, I am currently learning and started last year. Please let me know areas to improve and places for further reading and practicing. Thank you!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
