Higher Order Functions/Functions as Data

I am working on the JS lesson Higher Order Functions > Functions as Data. I have this current code:

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

// Write your code below
const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;

is2p2();

console.log(is2p2(is2p2.name));

However, this actually outputs undefined even though it should be outputting checkThatTwoPlusTwoEqualsFourAMillionTimes, right? I’m confused as to why it’s putting out “undefined” but I passed the lesson.

Hey @betawhiz21505,

You are getting an undefined because the function is not returning an output. All it does is console.log inside the function. In order for the function to return something you will have to specify this inside the function like so:

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      return 'Something has gone very wrong :('; // the moment it finds one instance where 2+2 is not 4 it will break of the function and return this string
    }
  }
  return 'It does!'; // If all 100000 checks are ok, it will return this string.
};
1 Like
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      return 'Something has gone very wrong :('; // the moment it finds one instance where 2+2 is not 4 it will break of the function and return this string
    }
    return 'It does!'; // If all 100000 checks are ok, it will return this string.
  }

Not sure you want that second return to be inside the loop.

3 Likes

Haha true, my bad :stuck_out_tongue: put it in the wrong spot. I edit my original post. Thanks @mtf

2 Likes