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 🙂

function droids(arr) {
  let result = '';
  arr.forEach(findDroids);
  return result;
}

function findDroids(value, index, arr){
  if (arr[index] == "Droids"){
    result = "Found Droids!";
  } else{
    result = "These are not the droids you're looking for."
  }
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"] 
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"] 
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."

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:

let result = ''; // Available everywhere

function droids(arr) {
  //let result = ''; // Available only at `droids` level
  arr.forEach(findDroids);
  return result;
}

function findDroids(value, index, arr){
  if (arr[index] == "Droids"){
    result = "Found Droids!";
  } else{
    result = "These are not the droids you're looking for."
  }
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"] 
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"] 
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."

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:

const arr = ["qqq", "www", "eee"]
console.log(arr.includes("qqq") ? "Found droids" : "Not found")
console.log(arr.includes("zzz") ? "Found droids" : "Not found")
Advertisement