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
x
20
20
1
function droids(arr) {
2
let result = '';
3
arr.forEach(findDroids);
4
return result;
5
}
6
7
function findDroids(value, index, arr){
8
if (arr[index] == "Droids"){
9
result = "Found Droids!";
10
} else{
11
result = "These are not the droids you're looking for."
12
}
13
}
14
15
// Uncomment these to check your work!
16
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
17
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
18
console.log(droids(starWars)) // should log: "Found Droids!"
19
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."
20
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
1
21
21
1
let result = ''; // Available everywhere
2
3
function droids(arr) {
4
//let result = ''; // Available only at `droids` level
5
arr.forEach(findDroids);
6
return result;
7
}
8
9
function findDroids(value, index, arr){
10
if (arr[index] == "Droids"){
11
result = "Found Droids!";
12
} else{
13
result = "These are not the droids you're looking for."
14
}
15
}
16
17
// Uncomment these to check your work!
18
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
19
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
20
console.log(droids(starWars)) // should log: "Found Droids!"
21
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:
JavaScript
1
3
1
const arr = ["qqq", "www", "eee"]
2
console.log(arr.includes("qqq") ? "Found droids" : "Not found")
3
console.log(arr.includes("zzz") ? "Found droids" : "Not found")