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 JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge, Part II Solution

Why use conditional statement in a function?

Hi guys,

can someone tell me what is the purpose of insert conditional statement in the function? When do we need to put conditional statement into a function and when not? What would be happen if we didn't put conditiona statement into it? Thanks

8 Answers

anil rahman
anil rahman
7,786 Points

Conditionals like the if statement is used when we want to do checks before something happens or we can do a certain thing depending on the outcome. Very powerful when writing logic.

For example you have money in your wallet and its different coins. You have a 10 pence coin a pound coin. You want to check how much money is in the wallet and add it to the count.

You can check using conditionals which type of coin and its value and add that specific value to a sum.

I understand the meaning of conditional statement but it's not clear when to use it in a function. Is it different to put conditional statement outside the function?

anil rahman
anil rahman
7,786 Points

No you can use it outside or inside functions the only difference is what you are checking in the if, the placement of the if shouldn't matter.

So, for this example, could it be possible to place the if statement outside the function and let the program work without any effect?

anil rahman
anil rahman
7,786 Points

No in the example in the video the if is depending on the passed parameters if you wanted the if to work outside the function you would need variables that you are using instead. The reason to use the function is so that you can pass in different values to the if by hardcoding them in or getting a user to do it. All depends on how the data will get to that conditional statement.

Another question... The return statement stands for an esle statement? I mean, if the if condition es not true, then the return stattement is evaluated?

Thanks again!

anil rahman
anil rahman
7,786 Points

Yes so the if will return its return statement if it's true but if it's not then it will return the other default return statement which is basically the same as using else but not needed in this case. :)

Thanks a lor for the explanation Anil! Now it' more clear! ;)