Nishaglobal Education logo

JavaScript functions: reusable blocks of code

Write JavaScript functions with parameters and return values, use default values and arrow functions, understand scope, and split a program into small, testable pieces.

Lesson 6 of 1335 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Define and call functions with parameters
  • Return values from functions and use the results
  • Write arrow functions and explain variable scope
Outline
  1. What you'll learn and why it matters
  2. Defining and calling a function
  3. Returning a value
  4. Default values
  5. Arrow functions
  6. Scope: where variables can be seen
  7. Practice
  8. Common mistakes
  9. Recap
  10. Quiz
  11. Mark lesson complete

What you'll learn and why it matters

As programs grow, you find yourself writing the same steps again and again: work out a price with tax, format a date, check a form field. A function gives a name to a set of steps so you can run them whenever you need, with different inputs. Functions are also how you respond to clicks and key presses in lesson 9.

Defining and calling a function

JavaScript
function greet(name) {
  console.log(`Hello, ${name}! Welcome to the café.`);
}

greet("Asha");
greet("Kofi");

Console (Chrome and Edge)

Hello, Asha! Welcome to the café.
Hello, Kofi! Welcome to the café.
PartHereMeaning
KeywordfunctionStarts a function definition
NamegreetWhat you call it by; a verb is a good choice
ParameternameA variable that receives the value passed in
Body{ … }The steps that run each time it is called
Callgreet("Asha")Runs the function; "Asha" is the argument

Defining a function does nothing on its own. The steps run only when you call it, with brackets.

Returning a value

Most useful functions return an answer so the rest of the program can use it:

lineTotal(40, 3)price = 40quantity = 3function lineTotalsubtotal = 40 * 3return subtotal * 1.05return sends back126const chai = lineTotal(40, 3); // chai is 126
Values go in through the parameters price and quantity; the function body works out price times quantity plus 5 percent tax; return sends the result, 126, back to the code that called it, where it can be stored in a variable.
JavaScript
function lineTotal(price, quantity) {
  const subtotal = price * quantity;
  return subtotal * 1.05;
}

const chai = lineTotal(40, 3);
const bread = lineTotal(60, 1);

console.log(chai);
console.log(bread);
console.log(`Order total: ${chai + bread}`);

Console (Chrome and Edge)

126
63
Order total: 189

return does two things: it sends a value back, and it ends the function immediately. Any lines after a return in the same block do not run.

JavaScript
function showDouble(n) {
  console.log(n * 2);
}

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

const a = showDouble(5);
const b = double(5);
console.log(a);
console.log(b);

Console (Chrome and Edge)

10
undefined
10

Default values

JavaScript
function priceWithTax(price, taxPercent = 5) {
  return price + (price * taxPercent) / 100;
}

console.log(priceWithTax(200));
console.log(priceWithTax(200, 18));

Console (Chrome and Edge)

210
236

If the caller leaves out an argument, the parameter uses its default. Without a default, a missing argument is undefined, which often leads to NaN.

Arrow functions

Arrow functions are a shorter way to write a function and are very common in modern JavaScript, especially for small jobs like the array methods in lesson 7 and event handlers in lesson 9.

JavaScript
const square = (n) => n * n;

const describe = (name, age) => {
  const group = age < 18 ? "junior" : "adult";
  return `${name} (${group})`;
};

console.log(square(7));
console.log(describe("Ravi", 15));

Console (Chrome and Edge)

49
Ravi (junior)
FormExampleNote
Function declarationfunction square(n) { return n * n; }Can be called from anywhere in the file
Arrow, one expressionconst square = (n) => n * n;The value after => is returned automatically
Arrow, with a bodyconst f = (n) => { … return …; };With braces you must write return yourself

Scope: where variables can be seen

Variables created with let or const inside a function (or any { } block) exist only inside it. This is called scope, and it stops functions accidentally changing each other's variables.

JavaScript
function makeTea() {
  const cups = 2;
  console.log(`Making ${cups} cups`);
}

makeTea();
console.log(cups);

Console (Chrome and Edge)

Making 2 cups

The console shows this error

Uncaught ReferenceError: cups is not defined

Practice

Guided exercise

Temperature converter

Write a function toFahrenheit(celsius) that returns the temperature in Fahrenheit (multiply by 9, divide by 5, add 32). Print the result for 0, 37 and 100.

  1. Define function toFahrenheit(celsius) { … }.
  2. Return celsius * 9 / 5 + 32.
  3. Call it three times inside console.log, using a template literal for a clear message.
Show the solution
Solution
function toFahrenheit(celsius) {
  return celsius * 9 / 5 + 32;
}

console.log(`0°C = ${toFahrenheit(0)}°F`);
console.log(`37°C = ${toFahrenheit(37)}°F`);
console.log(`100°C = ${toFahrenheit(100)}°F`);

Console (Chrome and Edge)

0°C = 32°F
37°C = 98.6°F
100°C = 212°F

How to get there: The function does one job and returns the answer, so the same code works for any temperature. Each call's result is placed straight into the message.

Your turn

Initials

Write an arrow function initials that takes a first and last name and returns their capitalised first letters, like initials("meera", "iyer") → "MI". Print the result for two names.

Show the solution
Solution
const initials = (first, last) => (first[0] + last[0]).toUpperCase();

console.log(initials("meera", "iyer"));
console.log(initials("kofi", "mensah"));

Console (Chrome and Edge)

MI
KM

How to get there: A string can be read by index like an array, so first[0] is its first letter. The one-expression arrow function returns the joined, upper-case letters automatically.

Common mistakes

Forgetting the brackets when calling

You see: Nothing happens, or the console shows the function's code

Fix: Call with brackets: greet(), greet("Asha").

Using console.log instead of return

You see: The result is undefined when you try to use it

Fix: Return the value, then log it where you call the function.

Writing code after return

You see: Those lines never run

Fix: Put everything the function must do before return.

Using a function's inner variable outside it

You see: ReferenceError: … is not defined

Fix: Return the value and store it in a variable outside.

Forgetting return in an arrow function with braces

You see: The function returns undefined

Fix: With { } you must write return; without braces it is automatic.

Recap

  • A function names a set of steps; it runs only when called with brackets.
  • Parameters receive values; return sends a result back and ends the function.
  • Defaults fill in missing arguments; arrow functions are a short form.
  • Variables declared inside a block stay in that block's scope.

Key terms

Function
A named, reusable block of code.
Parameter and argument
A parameter is the variable in the definition; an argument is the value passed in a call.
Return value
The value a function sends back to the code that called it.
Scope
The part of a program where a variable can be used.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. What does `add(2, 3)` return? function add(a, b) { console.log(a + b); }

  2. 2. What does `const triple = (n) => n * 3; triple(4)` give?

  3. 3. With `function hi(name = "friend")`, what does `hi()` use for name?

  4. 4. A variable is declared with const inside a function. Where can it be used?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.