DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for HELP // Trying to print even and odd numbers
Joe Ashwell
Joe Ashwell

Posted on

HELP // Trying to print even and odd numbers

Hey All,

I've just started out with JavaScript and was trying to play around with modifying & printing to the DOM.

My aim was to print the numbers 1 - 100 with a description after explaining if they were even or odd.

I.e.

The number 1 is odd
The number 2 is even
The number 3 is odd
.
.
.
The number 100 is even

This is what I've been trying:

const numberDiv = document.querySelector('div#numberDiv');
const numberArray = [];

for ( let i = 1; i <= 100; i++ ) {
  if ( i % 2 == 0 ) {
    numberArray.push(`<p>The number ${i} is even</p>`);
  } else {
    numberArray.push(`<p>The number ${i} is odd</p>`);
  }
}

numberDiv.innerHTML = numberArray;
Enter fullscreen mode Exit fullscreen mode

The best way I have found so far is to push the value on each loop to an array and then print the entire array. However, it's now printing a comma on a separate line, like so:

The number 1 is odd

,
The number 2 is even

,
The number 3 is odd

etc.

I know array items are separated by a comma within the array, but thought that they weren't shown when the array was printed -- as normally you'd have to use the .join(', ') method to include the comma.

The two main questions I have are:

1) What would be the best solution to this problem?
2) What's going wrong with my code?

Thanks in advance.

✌️

Top comments (3)

Collapse
 
nickytonline profile image
Nick Taylor • Edited on

Based on your current code, the easiest thing to do would be to modify this line

numberDiv.innerHTML = numberArray;

to

numberDiv.innerHTML = numberArray.join('’);

Also, the reason the comma appears under your paragraph with spacing is because the paragraph element’s style for display is block. The comma is just a text node in the DOM.

In terms of the best way to do this, updating innerHTML With a joined array seems fine.

Hope that helps!

Collapse
 
ja profile image
Joe Ashwell

Ahhh awesome! Got it all working now, thanks for your help!

N.B. There was a small error in your code above, just an apostrophe and a back tick in the brackets, as opposed to two apostrophes. - I wasn't sure if you were trying to catch me out πŸ˜‚.

Thanks again Nick, much appreciated!

Collapse
 
nickytonline profile image
Nick Taylor

Ah, I was on mobile. I must have picked the wrong one when closing the empty string. Glad it’s all sorted.

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.