Skip to content
Advertisement

How do I get the function I pass through forEach to reference variables in other scopes?

I don’t know why my findDroids function cannot reference the result variable within my droids function. When I run this code, I get “result is not defined”. Any tips/guidance is greatly appreciated. I’m new to Javascript, so please go easy on me 🙂

JavaScript

Advertisement

Answer

Because in JS let variables are scoped to its nearest function. In this case result is only available at droids level. Making the variable global should work:

JavaScript

Having said that, using a global variable is probably not the best thing. You can find a needle in a haystack with haystack.includes(needle) to easily check if an array includes the value you are looking for:

JavaScript
Advertisement