FAQ: Iterators - The .findIndex() Method


#1

This community-built FAQ covers the “The .findIndex() Method” exercise from the lesson “Iterators”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The .findIndex() Method

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

I have a question about JavaScript.
In the code below, I noticed that the argument of the function uses the variable “animal”, as in “animal === ‘elephant’”
However, the array was declared with the function “animals” not “animal,” so how does the script “know” that animal is an item in the array “animals”
I have noticed with with a few other pieces of code, such as where an array is declared as “numbers” and later a function is passed the argument “num”. But “num” and “animal” were never declared as variables by the code. How does this work and what are the rules around it?

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex(animal => {
return animal === ‘elephant’;
});


#3

The variable is defined in the loop.

for (let animal = 0; animal < animals.length; animal++) {

}

#4

Would anyone be able to explain why the ?true : false was at the end of the code?

return animal[0] === ‘l’ ? true : false;


#5

That is a control flow device known as a ternary expression. The term refers to three components.

condition ? true case : false case
//        ^           ^
//     ternary      colon
//     operator    separator

#7

Can someone pleeease help me and describe what’s going on here as codeacademy does a really bad job. In this exercise they say:

"

…in the callback function.

const jumbledNums = [123, 25, 78, 5, 9];

const lessThanTen = jumbledNums.findIndex(num => {
return num < 10;
});

  • jumbledNums is an array that contains elements that are numbers.
  • const lessThanTen = declares a new variable that stores the returned index number from invoking .findIndex() .
  • The callback function is an arrow function has a single parameter, num . Each element in the jumbledNums array will be passed to this function as an argument.
  • num < 10; is the condition that elements are checked against. .findIndex() will return the index of the first element which evaluates to true for that condition.

"

What is the callback function in the code and why do we need it? Thank you.


#8

Update: here’s the solution I found but I have no idea what’s happening or why it works, please can you describe it for me?:

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex(animals => {
return animals === ‘elephant’;
});


#9

The only reason I’m getting these right is because it’s the same code pattern over and over again on every exercise.


#10

This is the callback…

num => {
  return num < 10;
}

which may also be written in relaxed syntax,

num => num < 10

as in,

const jumbledNums = [123, 25, 78, 5, 9];
const lessThanTen = jumbledNums.findIndex(num => num < 10);

#11

Thanks very much - I found this video online which finally allowed me to understand this:


#12

Hi! if this code is right:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {
  return animal === 'elephant';
});

so why isn’t this one?

const startWithS = animals.findIndex(animal => {
    return animal[0] === 's';
});

What I mean is: .findeIndex() method return index of first element in the array which evaluates to true. Why code works in first example (evaluates to true) but doesn’t in second one? Same comparison operator is used (===). And how should code look like if I didn’t want to use ternary operator but just an if statement? this one won’t work:

const startWithS = animals.findIndex(animal => {
  if (animal[0] === 's') {
    return animal;
  };
});

Thanks in advance!


#13

array.findIndex() will return the index of the value that satisfies the test condition.

if (array.findIndex(element => element === 's')) === 0)

The method returns the index of the string element the starts with 's'. If it is zero, then we know that the string starts with ‘s’.


#14

Your first example is correct, but the variable name is not well written.
The variable name is ‘startsWithS’ and does not ‘startWithS’.


#15

Hey, thx a lot! It was one of these times that one starts to feel kinda schizofrenic :wink:

thx!


#16

Follow-up question here. Has anyone tried employing .charAt() which is given as alternate method in hint #2?

I’m probably doing things wrong, but it doesn’t seem to be recognizing .charAt().

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const startsWithS = animals.charAt(letter => {
  return letter[0] ===  XXXX
});

I didn’t finish the code block (hence the gibberish) because regardless of what I put in, it didn’t get past the fact that it wasn’t recognizing .charAt(). I’m getting the error:

/home/ccuser/workspace/javascript-iterators-find-index/main.js:12
const startsWithS2 = animals.charAt(letter => {
                             ^

TypeError: animals.charAt is not a function
    at Object.<anonymous> (/home/ccuser/workspace/javascript-iterators-find-index/main.js:12:30)

Any ideas? Am I missing something obvious?


#17

The String.charAt() method does not take a callback. It takes an index.

"string".charAt(0) === 's'   // true

Now we could use this as the function body of a filter callback…

startsWithS = animals.filter(x => x.charAt(0) === 's');

#18

Thank you so much for the reply and the time taken! I didn’t even consider that. It’s hard to step back and consider larger scale mistakes or assumptions you are making when you’re quite caught up in a flawed assumption.


#19

Don’t I know that. It can be embarrassing to be so far out in left field only to be pulled back in with a simple explanation of where we are wrong. I blush at least once a day.

It’s no sin to be wrong, and should not hold us back so long as we own it and are willing to take criticism and correction. Personally, I depend upon it.


#20

I’m taking advantage of the being wrong a lot, and am always happy to be corrected and shown things.

I find that I’m running into the problem of having difficulty understanding different-than-I’m-used-to syntax (I assume this is normal at my early stage). For example, I used your code block:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
startsWithS = animals.filter(x => x.charAt(0) === 's');
console.log(startsWithS);

And this returned [seal, salamander] which is great – but now I’m running into the problem of not knowing how to modify the code to make it select the first index that starts with ‘s’, and only that first index. What would be the way to make it return the singular value (in this case, seal) instead?


#21

Consider findIndex.

a = animals.findIndex(x => x.charAt(0) === 's')
// <- 3
b = animals[a]
// <- "seal"