Beginner level · Module 2: Logic and Functions in JavaScript · Lesson 3 of 3
Functions and Arrow Functions
Write reusable functions with parameters, default values and return values, using declarations and arrow functions.
In this lesson you will
- Write function declarations and arrow functions
- Use parameters, default values and block scope
Key concepts
function declarationarrow functiondefault parametersblock scope
The lesson
A function groups code under a name: function gradeFor(mark) { … return grade; }. Arrow functions are a shorter form: const gradeFor = (mark) => { … };. A one-expression arrow function can omit braces and return: const double = (x) => x * 2;.
Parameters can have defaults: function priceWithTax(price, rate = 0.1). A function without a return statement returns undefined, which is a common source of surprises when the result is used later.
Variables declared with let and const inside a block or function exist only there (block scope). Keeping variables local prevents different parts of a program from changing each other's data by accident.
Step by step
- Write gradeFor as a function declaration.
- Rewrite it as an arrow function.
- Add a default parameter to a tax function.
- Call a function that forgets to return and inspect the result.
Practice activity
Complete the school function library from the practical activity and test each function with at least three values.
Expected result: All functions return correct results for normal and edge-case values.
Check your understanding
-
What does a function return if it has no return statement?
Show answer
undefined.
-
Rewrite function square(x) { return x * x; } as an arrow function.
Show answer
const square = (x) => x * x;
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.