Do not refer to or call a function defined later in the file

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the functions category.

Last Updated: 2021-05-16

Generally, across most languages, you cannot refer to or a function before defining it (sometimes you might think otherwise due to certain structures like classes in some languages, but generally this is the case).

Therefore, especially when switching languages often, avoid referring to or calling functions before defining them.

Case in point, in React I got some extremely opaque and unhelpful errors when I passed a function not yet defined to useEffect. I wrongly imagined, that since it was a callback, it would be OK:

function QrComponent() {

  useEffect(requestCameraPermission, []);

  const requestCameraPermission = async () => {
    const { status } = await BarCodeScanner.requestPermissionsAsync();
    log("Camera permission is", status);
    setHasPermission(status === "granted");
  };
}

However, in fact, requestCameraPermission at this point was an undefined variable so it error-ed out. The fix was to switch the order:

function QrComponent() {

  const requestCameraPermission = async () => {
    const { status } = await BarCodeScanner.requestPermissionsAsync();
    log("Camera permission is", status);
    setHasPermission(status === "granted");
  };

  useEffect(requestCameraPermission, []);

}

Lesson

As a general rule, especially when you switch languages often, never refer to or call a function not defined until further down in the file.