1

Found this function in a project I am working on. And since I am rather new in JavaScript, I was wondering what is the difference between return; at the top, and then return null; at the bottom? Are there any differences or did someone just forget to type null??

  export function validCvr(value: string | number): ValidationResult {
    if (!value) {
      return;  // <-- HERE
    }

    value = value.toString();
    const CVR_REGEXP = /^[0-9]{8}$/;

    if (!CVR_REGEXP.test(value)) {
      return {
        [ValidationError.invalid]: true
      };
    }

    const weights = [2, 7, 6, 5, 4, 3, 2, 1];

    let sum = 0;
    for (let i = 0; i < weights.length; i++) {
      sum += weights[i] * parseInt(value.substr(i, 1), 10);
    }

    const isValid = sum % 11 === 0;
    if (!isValid) {
      return {
        [ValidationError.invalid]: true
      };
    }

    return null; // <-- HERE
  }
Ezrab_
  • 825
  • 5
  • 19
  • 44
RonRonDK
  • 425
  • 6
  • 22
  • 4
    `return;` will return `undefined`. The other returns `null`. – evolutionxbox Sep 19 '22 at 20:19
  • 1
    it's probably a mistake / sloppy style unless the code actually uses the result and does different things for `result === undefined` and `result === null`. For `if (!result)` or `if (result == null)` there's no difference. (`result == null` and `result == undefined` are equivalent to `result === null || result === undefined`). If you had [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks) enabled you'd see since now you have to define the return type as `ValidationResult | null | undefined` – zapl Sep 19 '22 at 20:59
  • Does this answer your question? [Is it better to return \`undefined\` or \`null\` from a javascript function?](https://stackoverflow.com/questions/37980559/is-it-better-to-return-undefined-or-null-from-a-javascript-function) – Tibrogargan Sep 19 '22 at 21:17

1 Answers1

2

to simply put it - return; is equal to return undefined;

Moonjsit
  • 630
  • 3
  • 11
  • So technically your statement is correct - but it does not answer the actual question being asked. Returning nothing and returning null are different things. Please see [What is the difference between null and undefined in javascript](https://stackoverflow.com/a/5076962/2487517) – Tibrogargan Sep 19 '22 at 21:22
  • @Tibrogargan well actually I think that @Moonjsit answered my question very well. My question was mostly about what `return;` returned. – RonRonDK Sep 20 '22 at 21:06
  • @RonRonDK you literally asked "what is the difference between `return;` at the top, and then `return null`". The answer simply does not provide an answer for that. – Tibrogargan Sep 21 '22 at 00:05