user1554264
user1554264

Reputation: 1224

Increasing understanding of evaluation/execution in JavaScript

For the following JavaScript code how would one work out the evaluation/execution order? Excluding Operator precedence, and focusing on the function squareList can one apply the principles of "Right to left" and "inside out" to the code?

What I mean by that is the first statement evaluated by JS in this case would be:

return num > 0 && num % parseInt(num) === 0;

One this has been evaluated for each item in the array, we will then progress to the line

return arr.filter(function (num) {

And finally:

return Math.pow(num, 2);

If I am thinking about this in the wrong way then I need some help please, how can I use a guide or official resouce to know the evaluation/execution order and what will be run first? and the statements following on from that in what order?

entire code block:

const squareList = function squareList(arr) {
  return arr.filter(function (num) {
    return num > 0 && num % parseInt(num) === 0;
  }).map(function (num) {
    return Math.pow(num, 2);
  });
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);

console.log(squaredIntegers);

Upvotes: 0

Views: 43

Answers (1)

TKoL
TKoL

Reputation: 13912

const squareList = function squareList(arr) {
  return arr.filter(function (num) {
    return num > 0 && num % parseInt(num) === 0;
  }).map(function (num) {
    return Math.pow(num, 2);
  });
};

So the first thing that happens is of course

arr.filter(function (num) {
    return num > 0 && num % parseInt(num) === 0;
  })

Where the internal function is ran on every element in the array, and for every element that that function returns true, the element is added into a resulting filtered array, and that filtered array then takes the place of the entire arr.filter(...) block of code

And then you've got

filteredArray.map(function (num) {
  return Math.pow(num, 2);
});

Where again, the internal function runs on every element, and the return value of that function is added to the NEXT final result array, a mapped array

And then finally you return it

return mappedArray

Upvotes: 1

Related Questions