Problem of exercise prime numbers

Hi guys,

I can understand what mosh did in the video. I am trying to do it another way but it always has problem. Can anyone tell me where the problem of my code is. thanks


function showPrimes(num) {

for (let number = 2; number <= num; number++) {

let result;

for (let factor = 2; factor < number; factor++) {

  if (number % factor === 0) {

    result = 'NO'
} else {
  result = number;


the result from the console.log() is always 2,3,4,5,6,7,8,9

From a quick glance, it’s probably because you’re never breaking out of your inner for-loop when result is ‘NO’, instead you continue and overwrite it.

if (number & factor === 0)
  result = 'NO'

Then it should probably work. Also in your first outer iteration, your result is going to be undefined because number === factor and it will skip your inside loop.

1 Like