Javascript Method

Please help me understand the code as I don’t know what’s going on.

Could you be more specific so we don’t have to go through and explain 30 different things if there is only one thing that is giving you pause?

Hi @kevinSmith
The ele2 is mentioned twice in the block of code. Why is that?

  const ele2 = element.substring(0, 2);
  return ele2 == "hi";

It is a variable holding a string. It is the string of the first two characters of element. It is mentioned twice because it is first declared/initialized and then it is used to make a comparison.

Personally, I think that is a terrible variable name. And one could argue that the variable is unneeded and could have just been:

  return  element.substring(0, 2) == "hi";

That’s kind of sloppy code anyway - the index parameter is never used. I think most modern developers, instead of this:

const arr2 = arr.filter((element, index) => {
  const ele2 = element.substring(0, 2);
  return ele2 == "hi";
});

… would have written this:

const arr2 = arr.filter(element => element.substring(0, 2) === 'hi');

Sometimes you do want to expand things out into extra lines that you don’t need, but I don’t see why that would be necessary here.

1 Like

Thank you @kevinSmith for the solution. It is now clear.
What you say is absolutely right, that the code is crappy. The source of the code is the book I am currently reading and practicing with. Would you please suggest a good javascript book that would change the way I learn things?
Thank you.

Would you please suggest a good javascript book that would change the way I learn things?

Not off hand. I’d just keep going with what you have. You may pick up some bad habits or idiosyncrasies, but that’s life - you’ll figure that out and fix it. That’s probably true of most methods. Of course, FCC has a course on JS. It’s pretty skimpy so I supplemented it with other books. I used to just go to the library and get a JS book and skim it and if I saw something I didn’t understand, I read that section. In the end, you will be learning from multiple sources so I wouldn’t worry about finding the “perfect” source.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.