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 Practice Object Interaction Starting with Some Methods Solution: Adding Methods to the Library Class

Daniela Fernandes Smith
PLUS
Daniela Fernandes Smith
Courses Plus Student 10,353 Points

Why doesn't this method have a return statement? It would work just the same, right, with or without a return statement?

Why doesn't this method have a return statement? It would work just the same, right, with or without a return statement? I'm curious why it was left out.

1 Answer

Hi Danella!

Functions and methods have return statements for three reasons primarily:

1) If the function/method is transformative (much like a toaster - you input bread, it returns toast).

For example:

const add = function(num1, num2) {
    return num1 + num2;
}

2) If you wanted to test a condition or the success or failure of the function/method's objective (thus returning true on success or false for failure) allowing for conditional program flow based on the outcome.

For example:

const isGreaterThan = function(num1, num2) {
  if (num1 > num2) {
    return true;
  } else {
    return false;
  }
}

3) A function or method that acts like a factory:

const makeNode = function(type, id, txt) {
    let node = document.createElement(type.toUpperCase());
    node.id = id;
    node.textContent = txt;
    return node;
}

Functions/methods without return statements are effectively merely subroutines that just encapsulate sections of code that need to be repeated multiple times, keeping your code DRY*.

*(Don't Repeat Yourself)

More info:

https://dzone.com/articles/is-your-code-dry-or-wet

So, in a nutshell, functions only need to return a value if doing so serves some purpose (such as creating a value or object to store in a variable), otherwise, it is not required.

Anyway, that's my take on it...!?!

I hope that helps.

Stay safe and happy coding!