Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ugultopu/3cc440b1f1287212fbb1944633e08b0e to your computer and use it in GitHub Desktop.
Save ugultopu/3cc440b1f1287212fbb1944633e08b0e to your computer and use it in GitHub Desktop.

Simply because of Automatic Semicolon Insertion (ASI). Because of ASI, for example if we put the return value (the thing to return) on the next line of the return keyword, nothing is actually returned. Example:

function provideGreetingSameLine() {
  return 'hello';
}

// Prints "hello".
console.log(provideGreetingSameLine());

function provideGreetingNextLine() {
  // Since there is nothing after the `return` statement on the same
  // line, a semicolon will be inserted (Automatic Semicolon Insertion),
  // making it equal to:
  // return;
  //   'hello';
  // Hence, nothing will actually be returned from this function, making
  // the return value undefined.
  return
    'hello';
}

// Prints undefined instead of "hello".
console.log(provideGreetingNextLine());

function provideGreetingWrappedInParentheses() {
  // Will evaluate whatever is within the parentheses and return that.
  return (
    'hello'
  );
}

// Prints "hello".
console.log(provideGreetingWrappedInParentheses());

Hence, because of ASI, whenever we put out JSX on the next line after the return keyword without wrapping the JSX within parentheses, undefined will be returned instead of the result of our JSX. For code organization and aesthetics, putting the JSX after the return keyword (instead of on the same line with the return keyword) is a good practice. Hence, because of ASI, if we want to put the JSX after the return keyword, we have to wrap it within parentheses for correct operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment