Tutorials / JavaScript Fundamentals / Functions: declarations, parameters and return values

Functions: declarations, parameters and return values

14 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

What a function is

A function is a named block of code that you can run whenever you want. You write it once, then call it from anywhere. It can take values in (parameters) and give a value back (the return value).

Functions are the main way we organise code. If you ever copy and paste the same five lines in two places, that is a sign you need a function.

Declaring and calling

function greet(name) {
  return "Hello, " + name + "!";
}

const message = greet("Sara");
console.log(message);          // Hello, Sara!
console.log(greet("Omar"));    // Hello, Omar!

The function keyword starts a declaration. greet is the name. name inside the brackets is a parameter, which is a placeholder for a value. When we call greet("Sara"), the text "Sara" is the argument, and it fills the placeholder.

return sends a value back and stops the function. The call greet("Sara") becomes that returned value, so we can store it or print it.

Return versus console.log

Beginners often mix these up. console.log prints something for a human to see. return hands a value back to the code that called the function.

function addPrinted(a, b) {
  console.log(a + b);
}

function addReturned(a, b) {
  return a + b;
}

const x = addPrinted(2, 3);   // prints 5, x is undefined
const y = addReturned(2, 3);  // prints nothing, y is 5
console.log(x, y);

A function with no return gives back undefined. Functions that calculate things should return their result, because then you can use it elsewhere. Printing is for the edges of your program.

Several parameters and default values

function calculatePrice(price, quantity = 1, taxRate = 0.17) {
  const subtotal = price * quantity;
  return subtotal + subtotal * taxRate;
}

console.log(calculatePrice(1000));         // 1170
console.log(calculatePrice(1000, 2));      // 2340
console.log(calculatePrice(1000, 2, 0));   // 2000

A default value is used when that argument is missing or undefined. Defaults must sit at the end of the list, so the required parameters come first.

If you call a function with too few arguments, the missing ones are undefined. If you pass too many, the extras are ignored. JavaScript does not warn you in either case, which is a good reason to check your calls.

One job per function

A good function does one thing and has a name that says what it is. Compare:

function isEven(n) {
  return n % 2 === 0;
}

function sumOfEvens(numbers) {
  let total = 0;
  for (const n of numbers) {
    if (isEven(n)) total += n;
  }
  return total;
}

console.log(sumOfEvens([1, 2, 3, 4, 5, 6])); // 12

isEven is tiny, but giving the check a name makes sumOfEvens read almost like a sentence. When something breaks, you only need to look at one small function. Small functions are also easier to test: you give an input and check the output, without touching the page or the network.

Functions are values

In JavaScript you can store a function in a variable and pass it to another function. This is the foundation for almost everything later in the course.

const square = function (n) {
  return n * n;
};

function applyTwice(fn, value) {
  return fn(fn(value));
}

console.log(square(4));              // 16
console.log(applyTwice(square, 3));  // 81

applyTwice does not know what fn does. It just calls it. A function that takes another function as an argument is called a higher-order function. The array methods you will meet soon, like map and filter, work exactly this way.

Hoisting

Function declarations are available before the line where you write them. This works:

console.log(double(4)); // 8

function double(n) {
  return n * 2;
}

Functions stored in a const, like square above, are not. Calling them above the definition gives an error. I put helper functions at the bottom of a file only when I am sure about this rule. Otherwise I define before use.

Common mistakes

  • Forgetting return. The function runs, but the caller gets undefined.
  • Code after return. Nothing after a return ever runs.
  • Calling without brackets. greet is the function itself. greet("Sara") runs it.
  • Changing too much inside. A function that quietly changes global variables is hard to reason about. Prefer to take inputs and return outputs.
  • Vague names. doStuff() tells the reader nothing. Use calculateTotal() or formatDate().

Try it yourself

  1. Write areaOfCircle(radius) that returns the area using Math.PI.
  2. Write isPalindrome(word) that returns true for words like "level". Hint: compare the word with its letters reversed, using split(""), reverse() and join("").
  3. Write formatName(first, last, title = "Mr.") that returns Mr. Ali Khan.
  4. Write repeat(fn, times) that calls a function a number of times. Test it with a function that logs a message.
javascript
function greet(name) {
  return "Hello, " + name + "!";
}

const message = greet("Sara");
console.log(message);          // Hello, Sara!
console.log(greet("Omar"));    // Hello, Omar!

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account