0

I'm trying to create a function that takes in two arguments. The first being a word and the second a single letter. I want to return true if the second argument is present in the first and false if it isn't. I'm trying to do this without the .includes() method.

function includes (strA, strB) {
  for (let i = 0; i < strA.length; i++) {
    if (strA.charAt(i) === strB) {
       return 'true'
    }else {
     return 'false'
    }
  }
}

includes('awesome', 'e')

Running the code doesn't return anything. Also when i try to console.log() strA[i] or strA.charAt(i) within the for loop only the first letter of strA is logged.

I'm pretty new so any help is appreciated. Thanks.

Georgi
  • 1
  • 1
    How do you know it doesn't return anything? You don't `console.log` the result? – kelsny Oct 03 '22 at 19:54
  • 3
    How about using the in-built string method `'awesome'.includes('e')`? – PeterKA Oct 03 '22 at 19:55
  • 1
    Your `return 'false'` should be outside of the loop – PM 77-1 Oct 03 '22 at 19:56
  • 2
    If you're going to return boolean values, use boolean types, not strings. – Rory McCrossan Oct 03 '22 at 19:56
  • Why not just `let checkMe = "awesome"; let x = checkMe.includes( 'e'); console.log(x);` – Mark Schultheiss Oct 03 '22 at 19:57
  • If the linked question does not answer yours please elaborate why so we may best assist you here. – Mark Schultheiss Oct 03 '22 at 20:03
  • Note in the linked there is also `return this.indexOf(search, start) !== -1;` so strictly speaking that does not use `includes()` there – Mark Schultheiss Oct 03 '22 at 20:06
  • Think about what happens: (1) You enter the for-loop for the first time with `i = 0`. (2) The character is `a`, you compare it with `e` (3) `a` is not `e`, so the `else` part of your if-statement gets executed. (4) It states: `return "false";`, so that is what happens. The function exits and gives you back the value `"false"` If the current character doesn't math the value you're looking for, **you don't do anything**. You just want the loop to continue and go to the next character. Only when the loop is done and you still haven't found the character, do you want to return false. – Sander Oct 03 '22 at 20:08

2 Answers2

0

You should only return false after the end of the loop rather than returning false directly inside the loop if the first letter does not match.

function includes (strA, strB) {
  for (let i = 0; i < strA.length; i++) {
    if (strA[i] === strB)
       return true;
  }
  return false;
}

console.log(includes('awesome', 'e'));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    @RoryMcCrossan The question states that "I'm trying to do this without the .includes() method." It seems that it is an exercise. – Unmitigated Oct 03 '22 at 19:58
0
function includes (a, b) {
   return a.indexOf(b) > -1;
}
Bruno Pfohl
  • 451
  • 1
  • 8