0

I cannot figure this one out.

string s has the value of "john".

my function is supposed to return whether the number of occurrences of mike and john in s are the same.

It correctly prints the count of mike to be 0. It correctly prints the count of john to be 1.

And yet, after checking for equality between the two, it returns true! why?

function solve(s) {
  // Write your code here
  var countm = (s.match(/mike/g) || []).length;
  var countj = (s.match(/john/g) || []).length;
  console.log(countm);
  console.log(countj);

  if (countm == countj) {
    return Boolean("true");
  } else {
    return Boolean("false");
  }

}
console.log(solve('john'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Mamun
  • 2,322
  • 4
  • 27
  • 41
  • 3
    This is because the "false" string is a [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). You can simply return the conditional statement, `countm == countj` – ryeballar Apr 26 '20 at 02:21
  • 2
    `Boolean("false") === Boolean("true") === true` – Nick Apr 26 '20 at 02:23
  • 3
    some observatiosn: return primitive booleans. Don't `return Boolean('true')`, just `return true;`. It's a basic JS primitive (and most other languages, too). Also, don't use `if (x) { return true} else { return false }`: just return that test: `return (countm === countj)`, done deal. On that note, don't use `==`, which tells JS to do whatever type conversion it needs to do to get to a result, use `===`, which is _strict_ equality. And finally, don't use `match`, use `test`: `(/john/).test(s)` (without `g`) will be a true or false value, so you don't need weird array fallbacks and `.length` – Mike 'Pomax' Kamermans Apr 26 '20 at 02:23

1 Answers1

1

Boolean() takes the string passed and checks its truthiness. Since your passing a string "true"/"false" in both cases their truthiness is correctly evaluated to true!

Remove the quotes and your code should work fine

But as others have commented, you should just return true or return false, or return the evaluation return countm === countj

Shmuli
  • 56
  • 6