# Function as an argument

I’m confused regarding this code

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong ');
}
}
};

const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
};

In the code above, I’m getting the output with a random number of 4 or sometimes 3 or 6

if my understanding is correct

we can rewrtie the code like this

const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong ');
}
}
let t2 = Date.now();
return t2 - t1;
};

However if we rewrite the code like this, I’m getting an output of 10.
can you help me understand this code

I ran them both and I get consistent times with each 3-4 seconds. The only error I see is that you don’t need funcParameter as a parameter the second time because you do the for loop inside the function timeFuncRuntime . So this is all you need the second time:

const timeFuncRuntime = () => {
let t1 = Date.now();
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :frowning: ');
}
}
let t2 = Date.now();
return t2 - t1;
};

The 1st time you run this function, you ask for a function as a parameter called funcParameter .
Well, when you call that function it should look like this:

timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes)

thanks for this, I made a mistake on rewriting the code.

I actually rewrite the code this way

function timeFuncRuntime () {
let t1 = Date.now();
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong ');
}
}
let t2 = Date.now();
return t2 - t1;
};

the result was, I’m getting 10 or sometimes 11 consistently. Why am I getting a different output compared to the original code??

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.