How to usea While Loop in Javascript

In this approach, we utilize a while loop to find the factors of the input number. We start iterating from 1 and continue until reaching the input number. For each iteration, we check if the input number is divisible by the current iteration value with a remainder of 0. If it is, then the current iteration value is a factor of the input number, and we add it to the list of factors.

Example: This example demonstrates the utilization of a while loop to find the factors of a given input number.

JavaScript
let n = 12;
let i = 1;
let factors = [];

while (i <= n) {
    if (n % i === 0) {
        factors.push(i);
    }
    i++;
}

console.log(factors);

Output
[ 1, 2, 3, 4, 6, 12 ]




JavaScript Program to Find the Factors of a Number

We have given the input number and we need to find all the factors of that number. Factors of the number are nothing but the numbers that divide the original input number evenly with the remainder of 0. Below we have added the example for better understanding:

Example:

Input: n = 10
Output: 1 2 5 10
Input: n = 12
Output: 1 2 3 4 6 12

Table of Content

  • Using For Loop
  • Using Spread Operator
  • Using the reduce method
  • Using the map method

Similar Reads

Approach 1: Using For Loop

...

Approach 2: Using Spread Operator

Here, we are finding the factors of the input number by using the simple and traditional method that is for loop. We are firstly iterating through the values of 1 to the input number (12). Then using the if condition, we are checking whether the n is exactly divisible or not. This is the simplest method to find the factors of the input number....

Approach 3: Using the reduce method

Here we are using the Spread operator of JavaScript and the keys method to find the factors of the input number given by the user. The factors are stored in the array and printed using the console.log function....

Approach 4: Using the map method

Here, we will be using the reduce method to iterate over the elements and find the factors of the input number specific to the variable. This uses the ES6 feature for iteration and stores the output factors in the array. Then we print these factors in the console....

Approach 5: Using a While Loop

Here, we are using the map method which creates an array by calling the specific function on each of the elements present in the parent array. Mostly, the map method is used to iterate through the array and call function on every element of the array....

Contact Us