Iterator .findIndex()

How is that when I try to log the following at the end, I get an error? console.log(animal) it is not returning elephant. Why?

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];
const foundAnimal = animals.findIndex(animal => {
return animal[0] === ‘elephant’;
});

Hey @java9898360319!
Would you mind telling us what error message you get?

The I get is as follow;

/home/ccuser/workspace/javascript-iterators-find-index/main.js:6
console.log(animal);
^

ReferenceError: animal is not defined
at Object. (/home/ccuser/workspace/javascript-iterators-find-index/main.js:6:13)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3

Ahhh that is because animal is a local variable created inside of this

Thus, it cannot be accessed out side of that code block.

A way to fix this would be to have that console.log line inside of the findIndex method

Oh now that makes much sense!!! Thank you!!

1 Like