1

This works, but I don't understand why:

function hasUppercase(input) {
  for (var i = 0; i < input.length; i++) {
    if (input[i] === input[i].toUpperCase()) {
      return true
    } else { 
      return false
    }
  }
}

console.log(hasUppercase("no"));
console.log(hasUppercase("Yes"));

How come the 'true' for the 'Yes' beats all the falses?

4
  • 3
    The return statement exits the function immediately. Commented Sep 16, 2017 at 16:38
  • 1
    That function is not working. hasUppercase("ayyLmao") returns false. Commented Sep 16, 2017 at 16:40
  • 1
    Your function checks only the first letter of the word Commented Sep 16, 2017 at 16:42
  • No, it's not working. It might seem it worked because the first character (input[0]) you're testing for matches the case but take it off and you'll see for yourself Commented Sep 16, 2017 at 16:43

3 Answers 3

1

For all characters, you could just return (early exit) if you have found one uppercase letter - in cases of lower case, you need to iterate to the end of the string.

function hasUppercase(input) {
    for (var i = 0; i < input.length; i++) {
        if (input[i] === input[i].toUpperCase()) {
            return true;
        }
    }
    return false;
}

console.log(hasUppercase("no"));
console.log(hasUppercase("Yes"));
console.log(hasUppercase("yeS"));

Sign up to request clarification or add additional context in comments.

3 Comments

That's almost an exact copy of the answer I posted a few minutes earlier
It really makes a SIGNIFICANT difference
Thanks so much! Return causes the function to exit immediately, I didn't realise.
0

Your problems are due to the return false statement, which makes function return on first non-uppercase character. The way it is constructed, it will always return after first character. Others already gave you solutions, I'll give you more concise way to achieve the same:

ES2015 (ES6)

const hasUpperCase = in => in.split('').some(c => c === c.toUpperCase());

// Demo:
console.log(hasUpperCase('no'));
console.log(hasUpperCase('yeS'));

Previous versions

function hasUpperCase(input) {
  return input.split('').some(function isCharUpperCase(char) {
    return char === char.toUpperCase();
  });
}

// Demo:
console.log(hasUpperCase('no'));
console.log(hasUpperCase('yeS'));

Comments

0

This function checks only the first character of a given input. If the first character is in Uppercase then it returns true else it returns false. The function quits after first iteration.

So if the given input is like 'yEs' then it returns false. As it checks only the first character 'y' and exits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.