Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why is conditional statement first?

Hey guys! I am curious why is conditional statement first inside function? I know that code won't run if return would be first, but still.. don't get it? Is there any rule which must go first inside functions? Thanks for your help! Best Regards, Danny

function getRandom(lower,upper){
  if (isNaN(lower) || isNaN(upper)){
    throw new Error ('Something is wrong!');
  }
  return Math.floor(Math.random() * (lower - upper + 1)) + lower;
}

console.log(getRandom(5,6));
console.log(getRandom('Nine',6));
console.log(getRandom(5,'Five'));

2 Answers

No rule about conditional statement ordering; they can appear in any order inside a function.

However, in the above code, the conditional is ordered first because it is validating the arguments passed into the function. If either argument is NAN (Not a Number), then the function will throw an error. The conditional appears first because it wants to validate the arguments first.

ahha! I got it! thanks for you help buddy! :)