Search code examples
javascriptsyntaxparseintcode-organization

Difference in efficacy between parseInt() and Number.isInteger() in following Javascript array scenario?


I am working through freecodecamp.org's Javascript ES6 coding problems and one of them tasked me with using arrow function notation to:

  1. Take an array of real numbers.
  2. Filter only the positive integers into a new array, and
  3. Square those positive integers.

I have successfully completed the problem but built my code for Step 2 by filtering the original array with Numbers.isInteger(). Freecodecamp.org's provided answer utilizes parseInt().

I do not see why we would need to parse integers if they are already integers, nor why parseInt() does not throw an error since its parameter asks for a string.

My primary question: Are both equally acceptable? Is one going to get me into more trouble down the road?

The only closely relevant stackoverfow I found was here (which was vaguely helpful). Below is my code followed by the answer code provided by freecodecamp.org. NOTE: I am aware my code has a few extra steps in it. I am not a huge fan of arrow notation and am still improving my code-organization!


MY CODE::

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

const squareList = (arr) => {

"use strict";

// dictates what numbers are filter()'d out of original array

const checkElement = (value) => value > 0 && Number.isInteger(value) == true;

const integersOnly = arr.filter(checkElement); //filters ONLY positive integers into new array

PROVIDED ANSWER CODE::

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

const squareList = (arr) => {

"use strict";

const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );

Solution

  • I do not see why we would need to parse integers if they are already integers.

    You don't need to. This is abuse of parseInt. They should have used Math.floor instead for their intented purpose.

    Why parseInt() does not throw an error since its parameter asks for a string?

    Because it's an old API, and it's very lenient. Instead of throwing errors, it simply coerces its argument to a string, then tries to parse that.

    My primary question: Are both equally acceptable?

    No, parseInt is absolutely inacceptable. You found a much better solution with isInteger. The reason why they didn't use it probably is that isInteger is a relatively new function, added with ES6.