0

Js function return problem(solved)

I am getting return value totally unexpected in js function.................... function isMatchFound(arr, key){ arr.forEach((e)=>{ if(key === e){ console.log('match found'); return true; } }); console.log('no match'); return false; } arr = ['key1', 'key2', 'key3']; key = 'key2'; console.log(isMatchFound(arr, key)); ----------------------------------------------------------- output in console............... match found no match false What is this behaviour?------- please help me

15th Jan 2022, 7:01 PM
saurabh
saurabh - avatar
2 Answers
+ 2
I think the problem is that "return true" only breaks/ returns from the inner function (forEach) but not from the outer function (isMatchFound). So the outer function will always return false. Btw, if you want to check if the array contains a key, you can simply do something like arr.includes(key);
15th Jan 2022, 7:13 PM
Lisa
Lisa - avatar
0
Ohh that's right, Thanks folk.......
15th Jan 2022, 8:19 PM
saurabh
saurabh - avatar