Problem with else clause in function

Hello,

I am writing a function that returns false if characters are repeated in a string and true otherwise.

The function works correctly when the condition is true, but when it’s false, both true and false values appear in the console, so there is obviously something wrong with the else part of the function.

Could someone help please?

  let tempArray = str.split("");
  tempArray.sort();
  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] == tempArray[i + 1]) {
      console.log(false);
      break;
    } else {
      console.log(true);
    }
  }
}

Hi, what happens if you leave out the break statement? They’re not usually used in if / else statements and might be leading to confusion here.

Hi!

Iioba is right and you don’t need an else statement for a boolean, as there are just two possible results.

Remove the else, add return true and return false to the respective console.logs and your code should work.

If I remove it, I get multiple trues and falses as the comparison in the loop continues (that is why I put it in)…

Thanks, I removed the else cluse, but it just results in a ‘true’ result returning nothing to the console.

Where should I put the console.log for true if not in an else statement?

Outside of the loop

function equalChars(str){
  let tempArray = str.split("");
  tempArray.sort();
  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] === tempArray[i + 1]) {
      console.log(true);
      return true //optional
      break;
        }
    }
  console.log(false);
  return false //optional
 
}

thanks

in the function I have below, the false value is in the loop and the true value outside of it (as you said), but the true value is showing up regardless of whether the condition is true or not as there is no condition attached to it.

Have I misunderstood something? Code below…

function isIsogram(str) {
  let tempArray = str.split("");
  tempArray.sort();
  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] == tempArray[i + 1]) {
      console.log(false);
      break;
    }
  }
  console.log(true);
}

Should I perhaps put in an ‘else if’ with the required conditions for the true value? Or can it be simpler than that?

I found the solution…below if anyone wishes to see it…thanks for all the help…

function isIsogram(str) {
  let result = true;
  let tempArray = str.split("");
  tempArray.sort();
  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] == tempArray[i + 1]) {
      result = false;
      break;
    }
  }
  console.log(result);
}
2 Likes

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