Write Higher Order Arrow Functions need explanation

Tell us what’s happening:

Hi everyone,
Can someone explain how

(num ^ 0) == num
and
num % parseInt(num) == 0

Exclude decimals in array? I got these from forum and hint. While my line is

num != parseInt(num)

It exclude positive integers.

Sorry for bad english, 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
  
  //use arrow function syntax
  const squaredIntegers =
  arr.filter(
    (num) => num > 0 //only positive integers
    && (num ^ 0) == num //exclude decimals 
    )
    .map(
      (num) => num * num //square and store the new array
    );

  // 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 (Windows NT 6.1; Win64; x64) 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/

parseInt(num), as the name implies, will parse the given number as an integer, so it will stop at the first non-integer portion it finds. Thus, not only will parseInt('123.45') return 123, something like parseInt('234abc567') will return 234.

The behavior of num ^ 0 returning an integer is because the ^ (bitwise xor) operator will coerce the left hand side to an integer. It also works with num | 0.

What all of these various tricks are doing are asking “is the integer portion of num equal to num?” If so, then num is an integer.

BTW, the modern way to determine if a number is an integer is Number.isInteger(num).

1 Like