Finally, array methods arrived to take down all those counter-based iteration functions.
I’m trying to find out how to use the optional ‘thisValue’ in map() method.
Couldn’t find many examples around, so I’m trying to figure out how to use it within an arrow function.
Regarding the code below:
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
// change code below this line
let squaredIntegers = [];
arr.map((val)=>{Math.floor(val) == val && val > 0 ? squaredIntegers.push(val * val) : "Not invited to the party"})
// change code above this line
return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
Can I use any of the native map() parameters to eliminate the need of declaring “let squaredIntegers = []” ?
what you should do is let squaredIntegers = arr.map()
and make sure that the callback returns a value, because map has a specific function, which is returning an array with items those of the array on which it is used but changed like the callback function say
to remove items you need to use filter(), the callback should return true or false and it returns an array with only the items for which the callback returned true
the way you are doing, the method you want to use is instead forEach, this method doesn’t return anything and just execute the callback for each item of ge array
doesn’t matter if it works fine, if you are not using the correct method, you are misusing things map returns an array, with the items changed based on the callback forEach execute a function (the callback) for each item in the array, doesn’t return anything
so if you want to use the method to push things somewhere else, forEach is more appropriate
let arr = [1,2,3,4].map(x => x+1) arr has value of [2,3,4,5]
you did the equivalent of this: let arr = []; [1,2,3,4].map( x => {arr.push(x+1);})
which is not how you use map. if you want to do this it is more appropriate to use forEach [1,2,3,4].forEach( x => {arr.push(x+1);}
yes, if you use map it does the same thing, but map does more than that so it is a waste of resources
Oh, so it’s not performance-friendly, good to know!
I was not presented to forEach yet, started studying JavaScript one month ago for about 1-2 Hrs/day (my whole spare time), a 13 days interruption included…
it’s there but not referenced with a variable
same situation as:
let str = "this string exist and it is referenced with a variable";
"this string exist but is not referenced with a variable - it still occupy space tho";
Now, I dunno if I am now abusing of your goodwill, but I still couldn’t figure out the use of the optional “thisValue” / “thisArg” in the map() method parameters structure…