A key thing to understand in any programming language is a function's return value: that is, the value that a function returns once it's finished running.

Return values in native functions

Let's look at the string split() method for the sake of this example. I happen to know that this method returns an array, but let's see how you could find this out for yourself in case you didn't already know.

The first thing to do is search for "mdn string split" in your favourite search engine; in the top few results, you should see the String.prototype.split() page in the MDN Web Docs.

If you scroll down, you should see a section called "Return value". Every function in the MDN Web Docs should have a section like this.

Reading it, we can see that the split() method returns an Array of strings, split at each point where the separator occurs in the given string.

Now let's look at an example:

const sentence = 'The quick brown fox jumps over the lazy dog';
const words = sentence.split(' ');

console.log(words); // ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

What we've done here is call the split() method and assign the returned array to the words variable.

Return values in your own functions

Let's write a trivial function that accepts a number and doubles it:

* Double a number
* @param {Number} num The number to be doubled
* @returns {Number} The result of doubling the number

function double(num) {
return num * 2;

The expression num * 2 is obviously what doubles the number, but it's the return statement that makes it the function's return value.

We could use our function like so:

const four = double(2); // 4

Like our previous example, what we've done here is call our double() function and assign the returned number to the four variable.

Chaining function calls

Hopefully this short post has been helpful. Armed with this knowledge, next week we'll look at how we can use it to chain calls to different functions.