Simple question for a complete beginner

Hello everybody,

I’m a complete beginner learning JavaScript, I use "freecodecamp " resources and recently decided to try a book as well. having a hard time with the “function return statement”. sometimes I see “return statement " come inside the “if statement” and other times it comes outside of the” if statement " can anyone clear this up for me, please? help appreciated. here are two examples of what I’m trying to say:

Example 1:

return is inside the if statement.

function getAvatar (points) {
var level = points / pointsPerLevel;

if (level == 0) {
return “Teddy bear”;

} else if (level == 1) {
return “Cat”;

} else if (level >= 2) {

return “Gorilla”;
}

Example 2:

return is outside the if statement :

var points = 0;
function playTurn(player, location) {
points = 0;
if (location == 1) {

points = points + 100;
}

return points;

}
var total = playTurn(“Jai”, 1);
alert(points);

Thanks in advance. I did not write this code it was copied from the book that I’m currently working on.

Return statements can be placed wherever the logic of the functions requires them to be.

3 Likes

Just to be clear, you may hear some (older) people say, “there should only be one return statement and it should be at the end of the program/function”. That is an old idea based on how programs used to work and because functions were often so large that it could cause confusion. But we don’t do that anymore - as said, there is nothing wrong with multiple return statements in a function, especially if you keep the function small enough that you can see what is happening.

4 Likes

Thank you very much!

A return inside an if will only exit the function if the statement is true. A return inside an else will only exit the function if the statement is false. A return outside of an if statement will always exit the function. Assuming that line of code is reached of course.

This is true for the execution of all code really and not just specific to returns.

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