Basic JavaScript: Return Early Pattern for Functions

Basic JavaScript: Return Early Pattern for Functions
0.0 0

#1

Hello fellow campers,

I would like to find out the difference between the following codes , thank you!:

//This is my code which is wrong because it does not satisfy : abTest(-2,2) should return undefined

function abTest(a, b) {
  // Only change code below this line
  if (a < 0,  b < 0 )     // HOW  IS THIS LINE  BEING INTERPRETED W/ A   COMMA INSTEAD OF  A  "||" 
  return 
  undefined

  
  
  // Only change code above this line

  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

// Change values below to test your code
abTest(2,2);

// SPOILER ALERT

// This is the right code :slight_smile:

function abTest(a, b) {
// Only change code below this line
if (a < 0 || b < 0 )

return
undefined

// Only change code above this line

return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

// Change values below to test your code
abTest(2,2);


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Also, your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#3

When you use a comma to separate two expression, it evaluates both expression but returns the value of the second (last if more than two) expression. The comma is an operator.

So, when you write:

if (a < 0,  b < 0 ) 

The only way the return statement gets executed, is if b < 0.


#4

Hello randelldawson,

Thank you for your feedback. It is quite helpful.