-1

Right now I am really stumped. I have a short function, called "validate", and for some reason the for loop I have prevents an outer for loop from running.

Here it is breaking by only printing out the first entry:

function validate(str) {
    for(i=0; i<str.length; i++) {
        // do nothing
    }
    return str;
}  

And here's the version that works:

function validate(str) {
    /*for(i=0; i<str.length; i++) {
        // do nothing
    }*/
    return str;
}  

Here is my fiddle. Here is the sample text file.

4
  • Try isolating your variable i. var i = 0; Commented Aug 3, 2017 at 17:42
  • post the code in the question, stackoverflow has same functionality as jsfiddle. but my guess is today you learn why var is not optional. Commented Aug 3, 2017 at 17:42
  • 2
    var i = 0; Always declare variables :/ Commented Aug 3, 2017 at 17:42
  • I just answered a very similar question here. Commented Aug 3, 2017 at 17:43

1 Answer 1

3

Try encapsulating your variable i. var i = 0;

function validate(str) {
    for(var i = 0; i < str.length; i++) {
        // do nothing
    }
    return str;
}

Without the var you are adding it to the global scope or the window object

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

1 Comment

Thank you! I am indeed an idiot today. I'll accept your answer shortly (there is a waiting period apparently for accepting an answer).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.