Mastering Average Calculation in JavaScript

Mastering Average Calculation in JavaScript

Mastering Average Calculation in JavaScript

  • PreCodeCamp Learning

  • 3 minute read

Calculating Averages in JavaScript: A Beginner's Guide

Welcome to this coding tutorial! Today, we’re diving into a common coding challenge: calculating the average of a string of numbers using JavaScript functions. If you’re a beginner, don’t worry—we’ll walk through every step together.

Understanding the Challenge

Our task is to create a function that takes a string of numbers, separated by spaces, and returns the average of those numbers. If the input string is empty, we should return zero. Let's break down the steps we need to accomplish this.

Introduction to the Challenge

Step 1: Setting Up the Function

First, we need to define our function. We’ll call it average. This function will take a string as a parameter. Here's how we can start:

function average(numString) {
    // Function logic will go here
}

Next, we want to handle the case where the input string is empty. We can do this with a simple if statement:

if (numString === "") {
    return 0;
}

Handling Empty Strings

Step 2: Converting the String to an Array

Now that we can handle empty inputs, the next step is to convert our string of numbers into an array. We can use the split method for this, which will split the string at each space:

let numbers = numString.split(" ");

This gives us an array of strings. However, we need to convert these string numbers into actual numbers to perform calculations.

Converting String to Array

Step 3: Looping Through the Array

With our array of strings in hand, we can now loop through it. We will use a for loop to iterate over each element:

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]); // Log each number
}

At this point, we can also check the type of each element to confirm they are still strings:

console.log(typeof numbers[i]);
Looping Through the Array

Step 4: Converting Strings to Numbers

To convert the string numbers into actual numbers, we’ll use parseInt:

let num = parseInt(numbers[i]);

Now we can accumulate the total by adding each number to a sum variable that we initialize before the loop:

let sum = 0;
sum += num;
Converting Strings to Numbers

Step 5: Calculating the Average

Once we have the sum of all numbers, we need to calculate the average. To do this, we divide the sum by the length of the numbers array:

return sum / numbers.length;
Calculating the Average

Final Code

Putting it all together, here’s what our complete function looks like:

function average(numString) {
    if (numString === "") {
        return 0;
    }
    let numbers = numString.split(" ");
    let sum = 0;

    for (let i = 0; i < numbers.length; i++) {
        sum += parseInt(numbers[i]);
    }

    return sum / numbers.length;
}

Now you can test this function with different inputs! For instance:

console.log(average("12 34 56 78 90")); // Should return 54

Practice Makes Perfect!

Don't forget to practice this on your own! You can try it out in a coding playground like JSFiddle to see it in action.

FAQs

What if I input non-numeric values?

Good question! You might want to add checks to ensure that each element can be converted to a number before performing the addition.

Can I use other methods to convert strings to numbers?

Yes! Besides parseInt, you can also use Number() or the unary plus operator (+) to convert strings to numbers.

Looking to Become A Developer?

We have tutorials and tutors that can make that happen!

Get Started w/ Becoming A Developer