Basic JavaScript - Return Early Pattern for Functions

Hi there just a small question, i ran this lesson twice to check and it passes both with this code

if(a<0||b<0 ){
return;}

as well as this code

if(a<0||b<0 ){
return undefined;}

was just wondering if there is a difference between letting the program define the undefined or defining it myself as undefined.

Its better to use conventional formatting:

if (a < 0 || b < 0) {
  return;
}

or

if (a < 0 || b < 0) {
  return undefined;
}

To answer your question - the two are the same.

Functionally they are the same.

In the case of an early return or a guard clause, the return value is not relevant unless hitting the guard is supposed to be an error. In this case, you might throw an error or return something other than just undefined.

Explicitly returning undefined isn’t really useful. An explicit return value should be something other than the default function return value.

If you are not expecting a return value, just return out of the function.

Thank you i thought this would be the case but expected something or other to be slightly inexplicit and obscure , in this case the " guard"
i am not familiar with this concept could you give a brief explanation?

The two are used interchangeably.

Personally, I think the word “guard” is more explicit about testing for correctness and as such, it should probably throw an error, or return something explicit that informs the caller, and not just return out of the function.

MDN throw example

function getRectArea(width, height) {
  if (isNaN(width) || isNaN(height)) {
    throw new Error('Parameter is not a number!');
  }
}

An early return is more like if this is true or not true let us just return out of the function.

function getInput(input) {
  if (!input) return;
}

Thank you very much for your time

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