I am working through freecodecamp.org's Javascript ES6 coding problems and one of them tasked me with using arrow function notation to:
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) );
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.