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.
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.
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;
}
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.
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]);
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;
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;
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
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.
Good question! You might want to add checks to ensure that each element can be converted to a number before performing the addition.
Yes! Besides parseInt, you can also use Number() or the unary plus operator (+) to convert strings to numbers.
We have tutorials and tutors that can make that happen!