Skip to content
FORGENO ADS GAMESUnlock all $8

JavaScript · Unit 2: Decisions, functions and loops · Lesson 3 of 6

Defaults and arrow functions

A parameter can have a default value, used when no argument is passed: function greet(name = "friend") { ...

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

A parameter can have a default value, used when no argument is passed: function greet(name = "friend") { ... }

Arrow functions are a shorter way to write functions, usually stored in a const: const double = (n) => n * 2; With one expression after the arrow, its value is returned automatically.

With curly braces, an arrow function needs return like any other: const add = (a, b) => { return a + b; };

Worked example

JavaScript

function greet(name = "friend") {
  return `Hi, ${name}!`;
}
const triple = (n) => n * 3;

console.log(greet("Mia"));
console.log(greet());
console.log(triple(5));

It prints

Hi, Mia!
Hi, friend!
15

Key terms

Parameter
An input named in a function's parentheses. It can have a default: (name = "friend").
Arrow function
A short function: (n) => n * 2. One expression after the arrow is returned automatically.

Practise it in Code Academy

It has 4 exercises (predict the output, fill in the blank and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.