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

Viewed 136

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."
2 Answers

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")

function droids(arr) {
  return arr.some(function(a){return a === "Droids";});
}

The 'some' suggestion. Check other examples for 'includes', probably a better tool for the job.

Related