0

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);
2
  • Getting familiar with Operator precedence helps. Outside of the operators and operands, JS statements are executed in the order they appear in the file, except functions, which are executed when invoked. Commented Dec 19, 2019 at 12:16
  • The order happens in the same order in which the functions are chained, first the filter (evaluating the conditional statement) for each item in the array, returning a new array, then the map (evaluating the Math.pow) for each item in the array, returning a new array Commented Dec 19, 2019 at 12:17

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.