I saw this code from an old post. (link:Use Destructuring Assignment to Pass an Object as a Function Parameters)
I also don’t understand why we had to return an identical function inside a function. I tried a different code below this code and it works fine. (read till the end before replying please) Can someone explain the point of having a function inside a function?
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = (function() {
"use strict"; // do not change this line
// change code below this line
return function half({max,min}) {
// use function argument destructuring
return (max + min) / 2.0;
};
// change code above this line
})();
console.log(stats); // should be object
console.log(half(stats)); // should be 28.015
I tried the code below and it also works
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = ({max,min}) => {
// use function argument destructuring
return (max + min) / 2.0;
};
// change code above this line
console.log(stats); // should be object
console.log(half(stats)); // should be 28.015
In this case the purpose was to enforce "use strict", I guess for students to use proper syntax and good conventions
To me it makes no sense and actually demonstrates bad conventions of naming and using same names for variables from outer scope, known as variable shadowing
To me I see this as a recursion where the an anonymous function was assigned to the variable half an immediately it was called to pass in the parameters and the statements. In otherwords without recursion it would have been;
> const half = function(){"use strict"};
after assigning the anonymous function the name of half then we say;
previously strict mode couldn’t be used in the global scope, so it was put in these functions that return an other function.
now strict mode is enforced in the background, this issue of needing to create the environment on where it is enforced is no more present