For example, I have this code:
var Foo = [1,2,3,4];
function searchInFoo(n) {
for(var i = 0, arrayLength = Foo.length; i < arrayLength; i++) {
if(Foo[i] === n) {
console.log("N: " + n + " found!");
} else {
console.log("N: " + n + " not found!");
}
}
}
searchInFoo(4);
Well, as I expected, an Foo array with n elements, I also have iterations of the for loop. It's great. Thus, if I call the searchInFoo function with any n parameter, my function will also execute all blocks in the if else statement n times. For example, in the above example, I once registered "n found" and three times "N: n not found!".
What is the best approach to avoid executing the else block without losing some of the basic error trap functions, which actually happens when I omit the block of whole blocks, like here:
var Foo = [1,2,3,4];
function searchInFoo(n) {
for(var i = 0, arrayLength = Foo.length; i < arrayLength; i++) {
if(Foo[i] === n) {
console.log("N: " + n + " found!");
}
}
}
searchInFoo(1);
source
share