The Missing Flag in a Function Error in JavaScript
Let's say we want to create a function that will take a digit and a number as parameters, and check if the specified digit is present in the number:
function func(needle, num) {
// code will be here
}
This is how we will use our function:
console.log(func('3', '12345')); // will output true
A certain programmer wrote a solution to this task:
function func(needle, num) {
for (let digit of num) {
if (digit === needle) {
return true;
} else {
return false;
}
}
}
This solution, however, works incorrectly.
The point is that the loop contains a condition
where in the very first iteration
either one return will execute,
or the other, thereby causing
an exit from both the loop and the function.
Let's rewrite our code correctly, using implicit flags in functions:
function func(needle, num) {
for (let digit of num) {
if (digit === needle) {
return true;
}
}
return false;
}