My goal is to halt a for loop once it reaches a specific input value. I managed to accomplish this task when executing the loop outside of a function. For instance, if I set the input variable to 'not leak', I want the loop to stop at 'not' and combine it with the keyword variable, which is 'leak', to display 'not leak'. However, when I tried integrating the loop into a function, it did not perform as expected and generated multiple results until the input variable matched the text variable. Instead, I only want it to output 'not leak'.
I experimented with different function formats, such as assigning the function as a variable, passing parameters to the function, and placing variables inside and outside the function without making any progress. It appears that the break if statement fails to work correctly once placed within a function. Any insights on why this happens and how to resolve it?
Here is the code inside a function:
function negKeyword() {
var keyword = 'leak';
var input = 'not leak';
var text = '';
var arr = ['no', 'not', 'checked', ''];
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
console.log(text);
}
}
negKeyword();
Below is the code executed outside a function:
var keyword = 'leak';
var input = 'no leak';
var text = "";
var arr = ['no', 'not', 'checked', ''];
for (i = 0; i < arr.length; i++) {
if (text===input) {break;}
text = arr[i] + ' ' + keyword;
}
console.log(text);