return statement does not work in forEach loop : <p>I'm trying to write a function <code>returnIndex</code> that returns the index of an object in an array, e.g. <code>myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }]</code>, by passing in a given key/value pair: e.g. <code>returnIndex(myArr, "name", "Bob")</code> should return <code>0</code>.</p>

<p>I tried this:</p>

<pre><code>const myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }]
const returnIndex = (arr, key, value) =&gt; {
    arr.forEach((item, index) =&gt; {
        if (item[key] === value) { return index }
    })
}

const i = returnIndex(myArr, "name", "Bob")
console.log(i)
</code></pre>

<p><strong>I get undefined i in the console.</strong></p>

<p>But when I create a throw-away variable i:</p>

<pre><code>const myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }]
const returnIndex = (arr, key, value) =&gt; {
    let i
    arr.forEach((item, index) =&gt; {
        if (item[key] === value) { i = index }
    })
    return i
}

const i = returnIndex(myArr, "name", "Bob")
console.log(i)
</code></pre>

<p><strong>Then it works.</strong> Why is it that I cannot return index directly but have to set up a throw-away variable i? I don't understand this -- Help please!</p>

<p>Also if you have a better way to solve this problem, please do share. Cheers!</p>
