0

I'm looking to answer the question, but most important to understand where I did it wrong and why. In a certain way to learn how to do it.

So, the question is:

We've already declared a variable for you in the editor called number to which the value 42 was assigned. Use a for loop to go through all numbers from number up to 50 (both inclusive), and check if they are multiples of 3. If they are, print them.

And I got to a point that I print to the console and I get the answer I want: 42, 45, 48.

But the console still gives me an error:

Remember the remainder operator? It might be of help to check if a number is a multiple of 3.

This is my code:

var number = 42;
var dividedbyThree = [];
for (var number = 42; number <= 50; number++) {
  if (number % 3 == dividedbyThree) {
    console.log(number);
  }
}

What am I doing wrong?

adiga
  • 34,372
  • 9
  • 61
  • 83

2 Answers2

1

Just replace

if (number % 3 == dividedbyThree)

with

if (number % 3 === 0)

DEMO:

var number = 42;
for (var number = 42; number <= 50; number++) {
  if (number % 3 === 0) {
    console.log(number);
  }
}
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • E.g., the automated test being applied to the code is looking for `number % 3 == 0` or `number % 3 === 0` and not finding it (because it has `number % 3 == dividedbyThree` instead, which coincidentally happens to work when `dividedbyThree` is `[]` because `0 == []` is true in JavaScript land). Which is why the OP is getting an error from whatever testing site they're using. – T.J. Crowder Feb 24 '20 at 11:37
0

The code will look like this

var number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
console.log(number); }
}

The number which returns 0 as the remainder when it is divisible by 3. So we check the remainder is equal to 0. if this condition satisfied console.log will print the number which is divisible by 3. if you need to push the numbers into new array, your code will look like this

var divBy3=[],number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
divBy3.push(number)
}
  console.log(divBy3)
}