Higher Order Arrow Functions parseInt()

Tell us what’s happening:
I’m working on the higher order arrow function problem, and I’m trying to understand why the parseInt() function is used here in the solution. ParseInt() parses a string and returns an integer. But there are no strings in the realNumberArray array.

Thank you!

Your code so far


const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
  "use strict";
  // change code below this line
  const squaredIntegers = arr.filter( (nums) => nums > 0 && nums % parseInt(nums) === 0 ).map( (nums) => Math.pow(nums, 2) );
  // change code above this line
  return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions

As explained in the MDN page about parseInt:

If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.

This means you can use parseInt even if the argument is not a string, so here is used as a way to “convert” a float number into an integer.

In my opinion using Math.floor would have been better, but they both achieve the same result.

2 Likes

Thank you! Did not catch this part where parseInt can also be used on non-string arguments on MDN. Documentation needs to be carefully read- lol

the .filter method being used on the array passed to the function, filter will run for each item in the array, so each itteration nums is a single element in that array, Same with array methods .map(), .reduce(), .find() etc…

1 Like

It is a slightly convoluted way to do the same as num % 1 == 0 or Number.isInteger(num).

1 Like