 # Beginner JavaScript Primer Questions

Beginner JavaScript Primer Questions
0

Hello everyone!

New guy here and that means time for easy beginner questions.
I am reading on https://docs.cocos2d-x.org/creator/manual/en/scripting/javascript-primer.html and I found this hard to grasp.

square = function (a) {
return a * a;
}
applyOperation = function (f, a) {
return f(a);
}
applyOperation (square, 10); // 100

I would like to run through it to see if I understand it correctly, please correct me if I am wrong.

1. We create a function called “square” which will take an argument of “a” and then return the value of “a * a”.

2. We create another function called “applyOperation” which will take two arguments, “f” and “a” and this will return f(a). Q: What does f(a) mean? Is it f * (a * a)?

3. We call the function “applyOperation” and feed in the function “square” and the value “10” which is an arbitrary integer applied to the value of “a”. Q: Shouldn’t it be square(f, a)? Does “f” here mean function?

Is this correct or do I missunderstand?

1. Correct

2. f(a) means f evaluated with a, given that f is a function which can take at least one parameter. As there are no typechecks in JavaScript, you have to be careful to call applyOperation only with arguments that make sense.

3. Yes, we call applyOperation and feed it the two parameters “square” and “10”.
In applyOperation, you can therefore think of f being replaced with square and a being replaced with 10, which results in square(10), which itself evaluates to 100.

Where do you mean, should it be square(f, a)?
“f” doesn’t directly mean “function”, you can parameters basically anyway you want. But the name “f” for a parameter that is supposed to be a function is convenient.

#2 is a pre-calculus topic, at least here in the USA we learn about this at that time. https://www.themathpage.com/aPreCalc/functions.htm

I assumed you already knew how to call a function and pass parameter(s). In JS, you can pass everything as a parameter.

For better understanding/reading, I re-wrote for you.

``````function square (a) {
return a * a;
}

function applyOperation (func, val) {
// you can call and pass parameter only when the provided parameter 'func' is a 'function'
// so make sure by checking its type before calling
if(typeof func == 'function')
return func(val);
}

// we are passing square function as a parameter
let result = applyOperation (square, 10);
console.log(result); // 100
``````
1 Like
1. Yes
2. The function applyOperation takes two parameters f and a. By looking the body of the function it expects the parameter f to be another function that is applied to the value of a. You can pass functions as parameters and use them inside another function.
3. In this case f is square. In the function applyOperation we expect two parameters f and a, f takes the form of the fuction square and a takes the value of 10

.