BeginnerLesson 7 of 305 min read

Functions: parameters, return values and arrow functions

Write reusable functions with parameters, return values, default values and arrow syntax, and understand scope.

In this lesson you will

  • Declare and call functions
  • Use parameters and return values
  • Write arrow functions
  • Understand local and global scope

About 17 minutes

Teach the computer a new word

Imagine you have a recipe for tea that you make ten times a day. Every time, you do not re-read the steps; you just say “make tea”. A function works the same way. You write the steps once, give them a name, and then call the name whenever you need them. Functions make programs shorter, easier to fix, and easier to understand.

Declaring and calling a function

function greet() {
  console.log("Hello there!");
}

greet();   // Hello there!
greet();   // Hello there!

Writing the function does nothing by itself. It is only a recipe. The code runs when you call it by writing its name followed by brackets.

Parameters and arguments

Most functions need some information to work with. Parameters are the labelled slots in the definition. Arguments are the real values you pass in when calling.

function greet(name) {          // name is a parameter
  console.log(`Hello, ${name}!`);
}

greet("Sara");   // "Sara" is an argument
greet("Ali");

Write a function called square that takes a number and prints its square. Call it with 4 and 9.

// define square, then call it twice

function square(n) { console.log(n * n); }

function square(n) {
  console.log(n * n);
}
square(4);
square(9);

Returning a value

Printing is useful for testing, but real functions usually return an answer to whoever called them, so it can be stored or used in more calculations.

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

const total = add(3, 4);
console.log(total);            // 7
console.log(add(10, 5) * 2);   // 30
Good to know

When JavaScript reaches return, the function ends immediately. Any code after it inside the function never runs. A function with no return gives back undefined.

Write a function isAdult(age) that returns true when age is 18 or more. Print the result for 12 and 30.

// define isAdult
console.log(isAdult(12));
console.log(isAdult(30));

return age >= 18;

function isAdult(age) {
  return age >= 18;
}
console.log(isAdult(12));
console.log(isAdult(30));

Default values

function welcome(name = "friend") {
  return `Welcome, ${name}!`;
}
console.log(welcome("Sara"));   // Welcome, Sara!
console.log(welcome());         // Welcome, friend!

Arrow functions

Modern JavaScript has a shorter way to write functions, called arrow functions. You will see them everywhere.

const double = (n) => {
  return n * 2;
};

const triple = n => n * 3;          // one parameter, one expression
const add = (a, b) => a + b;        // return is implied

console.log(double(5), triple(5), add(2, 3));   // 10 15 5

A function stored in a variable like this is called a function expression. Both styles work. Regular function declarations are good for the main named steps of a program; arrow functions shine for short helpers.

Scope: where a variable lives

const site = "Skills in Minutes";   // global: visible everywhere

function show() {
  const message = "Hi";          // local: only inside show()
  console.log(message, site);
}

show();
console.log(typeof message);     // "undefined": it does not exist out here

Variables created inside a function exist only inside it. This is a good thing: functions cannot accidentally mess with each other’s variables. If you need a value from inside, return it.

Functions calling functions

function priceWithTax(price) {
  return price * 1.17;
}

function formatMoney(amount) {
  return "Rs " + amount.toFixed(2);
}

function showPrice(price) {
  console.log(formatMoney(priceWithTax(price)));
}

showPrice(100);   // Rs 117.00

Good functions are small and do one thing. A function called formatMoney that only formats money is easy to test and easy to reuse in every part of your site.

Write a function fullName(first, last) that returns first and last name joined with a space, in capital letters. Print fullName(“sara”, “khan”).

// define fullName
console.log(fullName("sara", "khan"));

return `${first} ${last}`.toUpperCase();

function fullName(first, last) {
  return `${first} ${last}`.toUpperCase();
}
console.log(fullName("sara", "khan"));
Common mistake

Forgetting the brackets when calling: greet is the function itself, greet() runs it. Another common slip is writing console.log inside a function and then expecting to use its result. Printing and returning are different things.

Name functions with verbs

calculateTotal, isValidEmail, getUserName. A good name makes the call read like a sentence and removes the need for a comment.

Worked example: a price calculator toolkit

Let us build a few small functions that a shop page would genuinely need, and see how they work together. Each does one job, and the last one uses the others.

const addTax = (price, rate = 0.17) => price * (1 + rate);
const discount = (price, percent) => price - price * percent / 100;
const money = (n) => "Rs " + n.toFixed(2);

function finalPrice(price, percent) {
  return money(addTax(discount(price, percent)));
}

console.log(finalPrice(1000, 20));   // Rs 936.00

Read finalPrice from the inside out: discount the price, add tax, format as money. Because every helper is tiny and named clearly, the code explains itself and you can reuse money on every page of the site.

Functions are values

In JavaScript a function is just another value. You can store it in a variable, put it in an array, or pass it to another function. That is what makes map and filter possible: they receive your function and call it for each item.

function twice(action) {
  action();
  action();
}
twice(() => console.log("Hip hip hooray"));

Write a function repeat(times, action) that calls action that many times. Use it to print Hello three times.

function repeat(times, action) {
  // your code
}
repeat(3, () => console.log("Hello"));

Use a for loop that calls action() each round.

function repeat(times, action) {
  for (let i = 0; i < times; i++) {
    action();
  }
}
repeat(3, () => console.log("Hello"));

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is the difference between a parameter and an argument?

  1. None
  2. A parameter is in the definition, an argument is the value passed in
  3. An argument is in the definition
  4. Parameters are numbers only

Parameters are slots; arguments are the actual values.

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

  1. 0
  2. null
  3. undefined
  4. An error

It gives back undefined.

How do you call a function named go?

  1. go
  2. go()
  3. call go
  4. run: go

Brackets run the function.

What is const f = (a, b) => a + b?

  1. A syntax error
  2. An arrow function
  3. A loop
  4. An object

It is an arrow function that returns a + b.

Where can a variable declared inside a function be used?

  1. Anywhere
  2. Only inside that function
  3. Only in loops
  4. In other files

Local scope keeps it inside.

Summary

  • A function is a named, reusable block of code.
  • Parameters receive values; return sends one back.
  • Arrow functions are a short syntax.
  • Variables inside a function stay inside.

Next lesson

Next: arrays, lists that hold many values.

Questions

When do I use an arrow function?

For short helpers and callbacks. Use regular declarations for main, named steps.

Can a function return more than one value?

Return an array or an object holding several values.

What is a callback?

A function passed into another function to be run later. You will see them with arrays and events.

Progress is saved in this browser.