[Vuejs]-V-if function returning nothing, but it should

2👍

Because your return into forEach method, your main function doesn’t return anything. You can try to save in some variable returned data and after if statements return it. Or more easy way it use another loop like for of

2👍

As claimed in other answers, using for would be working but I will describe why it won’t work:

function functionWithForEach(arr) {
arr.forEach(a=>{
    if(a == "matched"){
        return "horrah";
    }
})
// here it is anonymous function
//The return exits the current function which is anonymous so it doesn't get returned
}

function functionWithForOf(arr){
    for(let a of arr){
        if(a == "matched"){
            return "horrah";
            // here it is not anonymous function
        }
    }
}

function functionWithPlainFor(arr){
    for(let index =0; index < arr.length; index++){
        if(arr[index]=="matched"){
            return "horrah";
        }
    }
}

function functionWithForEachVariable(arr) {
    let wordMatched = "";
arr.forEach(a=>{
    if(a == "matched"){
        wordMatched = "horrah";
        return "horrah";
    }
}
)
// see how the return does let code below it to execute
console.log("I will be called no matter return is called inside forEach");
return wordMatched;
}



let matchingArr = ["mat","matched","not correct"];

console.log(functionWithForEach(matchingArr),"from forEach");
console.log(functionWithForOf(matchingArr),"from for-of");
console.log(functionWithPlainFor(matchingArr),"from plain for");
console.log(functionWithForEachVariable(matchingArr),"from forEach with Variable");

It is clear from these that we can’t use forEach in this situation

If you wanna know more about these:

What does `return` keyword mean inside `forEach` function?

Short circuit Array.forEach like calling break

Why does this forEach return undefined when using a return statement

Leave a comment