javascriptarraysfunctionpromptfactoring

New to programming, can't figure out why this factor calculator doesn't work


I'm trying to make a factor calculator. You input a number, and it finds out the factors of that number. If you divide the original number by its factor you get zero, and I'm trying to implement that here so that when it returns with '0' it gets pushed to an array and that array is printed.

var number = prompt("Number?")
    
var array = []   
    
function modulo(a, b)
    {
    return a % b;
    }
    
 for (counter = 0; counter < number; counter++)  
    {
        var result = modulo(number, counter)
        if (result = 0)
           {
           array.push(counter) 
           }
    }
    
    for (counter = 0; counter < array.length; counter++)
    {
        alert(array[counter])
    }

What happens is the prompt shows up, I input a number, and nothing happens. Can anybody help?


Solution

  • Here is the problem, you have used = (Assignment operator) instead of == comparison operator

    for (counter = 0; counter < number; counter++)
    {
        var result = modulo(number, counter)
        if (result == 0) // in your code this is result = 0
        {
            array.push(counter)
        }
    }
    

    Working demo


    Complete code:

    var number = prompt("Number?")
    var array = []
    function modulo(a, b)
    {
        return a % b
    }
    for (counter = 0; counter < number; counter++)
    {
        var result = modulo(number, counter)
        if (result == 0)
        {
            array.push(counter)
        }
    }
    
    for (counter = 0; counter < array.length; counter++)
    {
        alert(array[counter])
    }