- Declare a function with parameters and call it with arguments
- Return a result with
returnand tell it apart fromconsole.log - Write arrow functions and know the rules of the short form
- Tell local and global variables apart
Suppose you need to calculate the discounted price of every product in an online shop. You could write the same three lines in ten places, but if you find a mistake in the formula, you would have to fix it ten times. Instead, you put the code into a function once, give it a name and simply call it wherever you need it.
Declaring and calling a function
A function is declared with the keyword function, a name, parameters in parentheses and a body in curly braces. Declaring is not running: the function works only when you call it by writing parentheses after its name. The values you pass in a call are called arguments.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Aysel');
greet('Murad');
greet('Leyla');▸ Expected output
Hello, Aysel! Hello, Murad! Hello, Leyla!
name is the parameter; 'Aysel', 'Murad' and 'Leyla' are arguments.return: giving back a result
Often a function calculates something and returns the result to the place where it was called. You write return for this. The returned value can be stored in a variable, used in another calculation or printed. As soon as return runs, the function ends. Without return, a function returns undefined.
function calculateArea(width, height) {
return width * height;
}
const room = calculateArea(4, 5);
console.log('Room:', room);
console.log('Two rooms:', calculateArea(3, 3) + calculateArea(2, 1));
function addNoReturn(a, b) {
const sum = a + b;
}
console.log(addNoReturn(2, 3));▸ Expected output
Room: 20 Two rooms: 11 undefined
A parameter can have a default value: it is used when no argument is passed.
function orderTea(size = 'medium', sugar = 1) {
return `${size} tea with ${sugar} sugar`;
}
console.log(orderTea());
console.log(orderTea('large'));
console.log(orderTea('small', 0));▸ Expected output
medium tea with 1 sugar large tea with 1 sugar small tea with 0 sugar
Arrow functions
An arrow function is a modern, shorter way to write a function: instead of the word function, you put the => sign after the parameters. If the body is a single expression, you leave out the curly braces and return — the value of the expression is returned automatically. The parentheses around a single parameter can also be dropped.
const square = (x) => x * x;
const add = (a, b) => a + b;
const shout = text => text.toUpperCase() + '!';
const sayHi = () => 'Hi!';
const describe = (name, age) => {
const group = age >= 18 ? 'an adult' : 'a teenager';
return `${name} is ${group}`;
};
console.log(square(7), add(2, 3));
console.log(shout('goal'), sayHi());
console.log(describe('Elvin', 15));▸ Expected output
49 5 GOAL! Hi! Elvin is a teenager
const double1 = (n) => n * 2;
const double2 = (n) => { n * 2; };
const double3 = (n) => { return n * 2; };
console.log(double1(5), double2(5), double3(5));▸ Expected output
10 undefined 10
Scope and functions as values
A variable created inside a function is local: it exists only inside that function. A variable created outside can be read from inside the function. This rule keeps functions separate from each other and prevents name clashes.
const siteName = 'Educora';
function showScope() {
const secret = 42;
console.log(siteName, secret);
}
showScope();
console.log(typeof secret);▸ Expected output
Educora 42 undefined
secret does not exist — typeof shows this.In JavaScript a function is also a value: you can store it in a variable and pass it to another function as an argument. A function passed to another function is called a callback. You will meet this idea everywhere in array methods and asynchronous code.
function repeat(times, action) {
for (let i = 1; i <= times; i++) {
action(i);
}
}
repeat(3, (step) => console.log(`Step ${step}`));▸ Expected output
Step 1 Step 2 Step 3
Write an arrow function toFahrenheit that converts degrees Celsius to Fahrenheit. Formula: celsius * 9 / 5 + 32. The function must return the result, not print it — the lines below do the printing.
const toFahrenheit = (celsius) => {
// return the temperature in Fahrenheit
};
console.log(toFahrenheit(0));
console.log(toFahrenheit(100));
console.log(toFahrenheit(-40));▸ Expected output
32 212 -40
Key points
- A function is a block of code written once and called many times.
- Parameters appear in the declaration, arguments in the call; parameters can have default values.
returnhands back the result and ends the function; without it the result isundefined.- The arrow function
(a, b) => a + breturns a single expression automatically; with{ }you needreturn. - Variables inside a function are local; functions can be passed around as values (callbacks).
Check yourself
10 questions. Every correct answer earns XP.
greet('Leyla'), what is 'Leyla'?