Using a helper function is pretty simple and it's a very useful tool that will help keep your code D.R.Y (Don't Repeat Yourself) and help you maintain the S.R.P (Single Responsibility Principle). Because of that it also makes our code easier to debug.
A helper function is a function that is called within another function, and we are able to use the return value from that function being called.
Example
In this example I'm going to show you how a helper function can be used:
function isPrime(number){
if(number < 2) return false;
for(let i = 2; i < number; i++) {
if(number % i === 0) return false;
}
return true;
}
function collectPrimes(numbers){
let primes = []
for(let i = 0; i < numbers.length; i++) {
let number = numbers[i]
if(isPrime(number)) primes.push(number)
}
return primes;
}
The goal was to create a function that filtered out only the prime numbers and returned them in a new array. In order to do that and maintain the S.R.P, I had to break down the problem into two.
The Breakdown
function isPrime(number){
if(number < 2) return false;
for(let i = 2; i < number; i++) {
if(number % i === 0) return false;
}
return true;
}
The isPrime (helper function) is taking in each number that is being sent up from collectPrimes (by calling it in the function and passing in the numbers) and checking if it is a prime number. If it is it will return true if not it will return false.
function collectPrimes(numbers){
let primes = []
for(let i = 0; i < numbers.length; i++) {
let number = numbers[i]
if(isPrime(number)) primes.push(number)
}
return primes;
}
Once it gets back down to the collectPrimes function the conditional checks if we got a truthy value back from the isPrime function, then it pushes that prime into the primes array and returns a new array of primes.
side note: We could also refactor this code and make it cleaner by using the .filter method, which will iterate through. filter out the primes, and return a new array of only the prime numbers.
return numbers.filter(number => isPrime(number))
(If you are not familiar with array iteration methods like .filter check out my previous blog post called The Fantastic Four: .map, .filter, .forEach, & .reduce array (iteration) methods).
Other Helpful Resources
What are Helper Functions, How to Use a Helper Function in JavaScript, Programming with Codecademy
Top comments (0)