To find the factors of a number in JavaScript, you can use a for loop to iterate through the numbers from 1 to the given number and check if the current number is a factor. If a number is a factor, it can be evenly divided into the given number without any remainder.
Here’s an example:
function findFactors(num) {
let factors = [];
for (let i = 1; i <= num; i++) {
if (num % i === 0) {
factors.push(i);
}
}
return factors;
}
let num = 12;
let factors = findFactors(num);
console.log("Factors of " + num + ": " + factors);
In this example, the findFactors
function takes a number num
as an argument and uses a for loop to iterate through the numbers from 1 to num
. If the current number is a factor, it is pushed into an array factors
. The function then returns the factors
array. The code then calls the findFactors
function with the num
value and logs the result to the console.
+ There are no comments
Add yours