Prime number detection in JS

Hello good people, as a novice programmer, I was assigned to write code in JS to detect a prime number or not. This is what I’ve done with all my little knowledge. This is very simple and devoid of complex code.

var num = 99;

    console.log("invalid input");

    for( var i=2; i<num; i++) {
            if(num % i==0){
                console.log(num + " is not prime");
                console.log(num + " is prime")

and the answer is

99 is prime

That’s not true. I know, many of you can write highly efficient code with advanced syntax. I do not expect such a sophisticated solution. What is actually missing in my code that can make my program functional?

What you are missing is the correct algorithm. Currently, your for loop only iterates one time. The for loop starts with i = 2, so your if statement checks if 99 % 2 == 0. It is not, so your else statement code displays 99 is prime to the console and you break out of the for loop and the code completes.

Describe what you think the correct algorithm is first (before writing any code) and we can help guide you till you have it and then you can start writing code.

1 Like

Thank you @RandellDawson, actually, I am just a one-week-old programmer. I don’t know about algorithm. I’ve reviewed many codes regarding this problem but those do not match my thinking pattern. Some people used function, some people used true/false syntax and so on so forth. I was wondering is it possible to edit this code with if-else and for loop technique? I thought the whole day but I can’t work with my code anymore.