Loop to check if number in var is Positive or Negative

Good evening!

I wanted to start learning HTML, and im having a hard time understanding the Loops. Im trying to make a code, that checks if the numbers in a variable are either positive or negative. If i have, lets say 5 numbers, the result should give 5 lines and each line like this The number "checkednumber " is negative.
This is what i have now, and i just cant get the hang of it.

edit: i cant paste my code, so i took a screenshot of it!

<!DOCTYPE html>

var numbers = [32,-4,-1.2,5,-340,4.5];
var x = 0;

while(numbers < 0){
    text += "<br> This number"checkednumber"is negative" // checkednumber should be the number im checking, so on the first line it should say 108.5
    text += "<br> This number"checkednumber"is positive"


Hi @Exonyan1, you have to format your code so that it shows up here; you can use the </> button for this. As for your question, there are several issues with your code:

  • The variable x isn’t used anywhere
  • Comparing an array to a number doesn’t make much sense; JS happens to evaluate numbers < 0 as false
  • To concatenate strings, you have to use the + operator like
    "This number is " + checkednumber + "is positive"
  • The variables text and checkednumber are not defined
  • You’re not doing anything with text

To iterate over an array, you can use a for loop:

var numbers = [32,-4,-1.2,5,-340,4.5]
var text = ''
var checkedNumber

for (var i = 0; i < numbers.length; i++) {
  checkedNumber = numbers[i]
  text += '<br> The number ' + checkedNumber

  if (checkedNumber < 0) {
    text += ' is negative'
  } else {
    text += ' is positive'

document.body.insertAdjacentHTML('beforeend', text)
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.