Home > Mobile >  Function with a for loop and if else statement- letters after
Function with a for loop and if else statement- letters after

Time:11-19

// YOUR CODE
let letters = '';

function lettersAfter(haystack, needle, limit){
    ('any value','a', 2);
    for(let i = 0; i < haystack.length; i  ){
        console.log(i);
        if(haystack[i] === needle){
            for(let j = 0; j < limit; j  ) {
                console.log(j);
             let innerChar = haystack[i   j   1];
            console.log(innerChar);
         letters  = innerChar;
         console.log(letters);

         }  
return letters;
        }
    }
}

// DO NOT EDIT BELOW

module.exports = lettersAfter;

I am doing tests (that are not written by me) and I should get the values listed below:

lettersAfter('any value','a', 2); // ==> ny lettersAfter('indefatigable', 'a', 4); // => tiga

I receive ==>nytiga

I can't figure out why it is pushing the two of them together, functions as much information that can be given is super helpful, I am a beginner!

CodePudding user response:

You have to move the letters variable initialisation into the function scope. That way every time you run the function the previous value gets erased.
Since the variable is globally-scoped so far, every value gets appended to the old value.

Also, please try to format your code a bit better next time. I advise using Prettier or some other code formatter.

I created a jsfiddle with the adjusted code, it can be found on this link.

function lettersAfter(haystack, needle, limit) {
  let letters = '';
  for (let i = 0; i < haystack.length; i  ) {
    if (haystack[i] === needle) {
      for (let j = 0; j < limit; j  ) {
        let innerChar = haystack[i   j   1];
        letters  = innerChar;
      }
      return letters;
    }
  }
}

console.log(lettersAfter('any value', 'a', 2));
console.log(lettersAfter('indefatigable', 'a', 4))

CodePudding user response:

Since letters is a global variable in context to the file where function exists it forms a closure with the function hence the value keeps appending . You can read more about closures here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

To avoid the closure you should always put the variable inside the lexical scope of the function.

  • Related