I am new to Javascript, and sturdying about the concept of higher order function, and using function as parameters.
I got two examples of code from online, and I do not understand what is going to happen.
First one, output will be 0, and I could not print the time of t1 and t2 ( I tried console.log(t1), but it became reference error). I wonder why it became 0. Also, I don't get how funcParameter() that is inside of functionbody is working for the function, though I know funcparameter() is callback function, and which is addOneToOne().
Second one, output will be 3. but how can it be 3 even though, I haven't put parameter into addTwo()? If I have not put anything in parameter, num will be automatically 0 or undefined?
I am sorry for many questions, but I really appreciate if you could help me out.
//1st code
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();//
funcParameter();
let t2 = Date.now();//
return t2 - t1;
}
const addOneToOne = () => 1 + 1;
timeFuncRuntime(addOneToOne);
console.log(timeFuncRuntime(addOneToOne))//0
//2nd code
const addTwo = num => num + 2;
const checkConsistentOutput = (func, val) => {
let firsttry = func(val);
let secondtry = func(val);
if(firsttry === secondtry){
return firsttry;
} else {
return 'This function returned inconsistent results';
}
};
checkConsistentOutput(addTwo,1)
console.log(checkConsistentOutput(addTwo,1))//3