@@ -20,6 +20,26 @@ console.log(find("code your future", "z"));
2020// Pay particular attention to the following:
2121
2222// a) How the index variable updates during the call to find
23+ // The index variable starts at 0. In every iteration of the while loop,
24+ // after the if check is performed, index increases by exactly 1 (index++).
25+ // This moves the "pointer" one character to the right through the string str,
26+ // ensuring that the function checks every character sequentially from left to right.
27+
2328// b) What is the if statement used to check
29+ // The if statement checks equality. Specifically, it asks:
30+ // "Does the character currently stored at the index position of the string match the char I am looking for?"
31+ // If the answer is true, the function immediately returns the current index, which exits the entire function.
32+ // If the answer is false, the loop simply continues to the next iteration.
33+
2434// c) Why is index++ being used?
35+ // index++ (which is shorthand for index = index + 1) is the loop advancement mechanism.
36+ // Without it, index would remain 0 forever.
37+ // This would cause an "infinite loop" where the program keeps checking the very first character of the string over and over again,
38+ // never moving forward to inspect the rest of the string.
39+
2540// d) What is the condition index < str.length used for?
41+ // This is the boundary condition (or loop guard). It ensures the code doesn't try to look for a character outside of the string's memory.
42+ // In JavaScript, if you try to access an index that doesn't exist, it returns undefined.
43+ // By ensuring index is always less than the length of the string, we guarantee that we only access valid positions.
44+ // Once index equals the length of the string, it means we have checked every single character without finding a match,
45+ // so the loop terminates, and the function returns -1 (indicating "not found").
0 commit comments