Skip to content

Beginner · Functions and closures · topic 11 of 61 · 25 min

Functions: declarations, expressions and return

Explanation

A function is a named, reusable block of code. You define it once and call it many times with different inputs. return sends a value back to the caller; without return a function gives undefined. In JavaScript functions are values, so you can store them in variables and pass them around.

Why functions?

Imagine calculating GST in twenty places in an app. If the rule changes, you must find and fix twenty copies, and you will miss one. A function puts the rule in ONE place with a name. Every other part of the program calls the name. Functions also make code readable: calculateGst(price) explains itself.

Function declarations

javascript
function calculateGst(price, rate) {
  return price * rate / 100;
}

console.log(calculateGst(1000, 18)); // 180
console.log(calculateGst(500, 5));   // 25
price and rate are parameters; 1000 and 18 are the arguments of the first call.

A parameter is a name in the definition. An argument is the actual value passed in a call. Defining a function does not run it; calling it with brackets () runs it.

return

return does two things: it ends the function immediately, and it hands a value back to whoever called it. Code after a return that runs is never reached. A function with no return, or with a bare return;, gives back undefined.

javascript
function logTotal(a, b) {
  console.log(a + b);   // prints, but returns nothing
}
const result = logTotal(2, 3); // prints 5
console.log(result);           // undefined
Careful: Printing is not returning. A function that only console.logs its answer cannot be used in further calculations: logTotal(2, 3) * 2 gives NaN, because undefined * 2 is NaN. If other code needs the answer, return it.

Function expressions

A function is also a value. You can create one inside an expression and store it in a variable. This is a function expression. Unlike a declaration, it cannot be used before the line where it is created (module 5 explains this, called hoisting).

javascript
const square = function (n) {
  return n * n;
};
console.log(square(9)); // 81

const tools = { square };     // stored in an object
console.log(tools.square(4)); // 16

Functions are first-class values

First-class means functions can be treated like any other value: stored in variables, put in arrays and objects, passed as arguments to other functions, and returned from functions. This one idea powers callbacks, array methods like map, event handlers and closures.

Pure functions and side effects

A pure function always returns the same output for the same input and changes nothing outside itself. calculateGst is pure. A function that writes to a file, changes a global variable or prints has side effects. Programs need side effects, but keeping most functions pure makes them easy to test and reuse.

Think of it like this: A pure function is like a calculator: 5 × 4 is always 20 and pressing the keys does not change anything else in the room. A function with side effects is like a vending machine: it gives you a drink AND changes its stock and cash box.
Tip: Name functions with a verb that says what they do: getUser, calculateTotal, isValidPin, formatDate. Keep each one small: if you need "and" to describe it, split it in two.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Functions: declarations, expressions and return · 1/6

Functions

In this lesson you will write your own functions: named blocks of code you can reuse.

Prefer a video by a teacher? Find free videos on “javascript functions declaration expression return tutorial” on YouTube ↗

In real life: One discount rule for a whole shopping site

An e-commerce site applies a festival discount on product pages, in the cart and on the invoice. The rule lives in one function. When marketing changes the cap from ₹500 to ₹750, one line changes and every page is correct.

javascript
function festivalDiscount(price) {
  const discount = price * 0.1;
  return Math.min(discount, 500); // 10% off, at most ₹500
}
console.log(festivalDiscount(2000)); // 200
console.log(festivalDiscount(9000)); // 500

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function area(length, width) that returns the area of a rectangle.

Task 2 · Code · Javascript

showTotal(prices) only prints the total, so the rest of the program cannot use it. Rewrite it so it RETURNS the sum of the array.

Task 3 · Code · Javascript

Write a function applyTwice(fn, value) that calls fn on value, then calls fn again on the result, and returns that. Example: applyTwice(n => n + 3, 10) returns 16.

Quick quiz

Question 1

1.What does a function return if it has no return statement?

Question 2

2.In function add(a, b) { … } and the call add(2, 3), what are a and b?

Question 3

3.function f() { return 1; console.log("hi"); } What happens when f() runs?

Question 4

4.Which function is pure?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does a function return if it has no return statement?

Answer: undefined

Every JavaScript function without a return value gives undefined.

In function add(a, b) { … } and the call add(2, 3), what are a and b?

Answer: Parameters

Names in the definition are parameters; the values in the call are arguments.

function f() { return 1; console.log("hi"); } What happens when f() runs?

Answer: Returns 1 and never prints

return ends the function; the next line is never reached.

Which function is pure?

Answer: One that returns a * b

a * b depends only on its inputs and changes nothing outside.

What is a function prototype?Related

Answer: A declaration: the function's first line ending with a semicolon

It tells the compiler the function's name, return type and parameter types before its body appears.

From Functions: declare, define, call and return

What does a function return if it has no return statement?Related

Answer: undefined

Without return, a function gives back undefined.

From Functions

Why can you call a function declaration above the line where it is written?Related

Answer: Hoisting: function declarations are ready before the code runs

JavaScript notes declarations before running. Function declarations are fully hoisted, unlike let and const.

From Scope, hoisting and closures

Which function is pure?Related

Answer: (a) => a * 2

Only a * 2 depends only on its input and changes nothing.

From Pure functions and immutability

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Functions and closures” before its exam: Arrow functions, Parameters: defaults, rest and options objects, Scope and closures, Higher-order functions and recursion.
  2. Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and objects. 61 topics left in the course before the final exam.

← Previous: Loop patterns that solve real problems