The purpose of return


#1

Considering this case:

function expandUrl() {
	const urlToExpand = url + '?shortUrl=' + $inputField.val() + '&key=' + apiKey;
  fetch(urlToExpand)
  	.then(
  		response => {
        if(response.ok) {
          return response.json();
        }
        throw new Error('Request failed!');
      },
    	networkError => {
        console.log(networkError.message);
      }
  	)
  .then(
  	jsonResponse => {
      $responseField.append('<p> Your expanded URL is </p><p> ' + jsonResponse.longUrl + '</p>');
return jsonResponse;
    }
  )
};

Why should I return jsonResponse if I’ve already filled the div id with the information I’m interested to fill with? I don’t understand clearly the purpose of this return.

Thx!


#2

in programming, we don’t just write code to complete a program.

what if the program needs to be expanded later? or changed? We might need to call the expandUrl() somewhere else, and then we don’t want to spend time debugging why expandUrl is not returning the right value, which is why we already add return

now, for a program this small, its not so problematic. But if you have 5000+ lines, good luck with it. I hope i made my point, you need to think ahead, functions must be flexible. The earlier you start with this modular thinking, the better.

return might not do much at the moment, and that is okay.