A function is a reusable block of code with a name. You write it once, then call it whenever you need it. Functions keep programs short, organised and easy to change: fix a bug inside a function and every place that uses it is fixed too.
Declaring and calling a function
function greet() {
console.log("Karibu to Skope Shop!");
}
greet();
greet();Karibu to Skope Shop! Karibu to Skope Shop!
The function keyword is followed by a name, round brackets and a body in curly braces. Writing the name with brackets, greet(), calls the function. Without the brackets, greet just refers to the function without running it.
Parameters and arguments
Functions become powerful when you give them input. Parameters are the names listed in the definition; arguments are the actual values you pass when calling.
function greet(name, town) {
console.log(`Habari ${name} from ${town}!`);
}
greet("Nekesa", "Bungoma");
greet("Kiprop", "Iten");Habari Nekesa from Bungoma! Habari Kiprop from Iten!
If you pass fewer arguments than parameters, the missing ones are undefined.
Returning a value
return sends a value back to whoever called the function. The call can then be used like any other value.
function addVat(amount) {
return amount * 1.16;
}
const total = addVat(1000);
console.log(total);
console.log(addVat(500) + 20);1160 600
return also ends the function immediately – any code after it in the same block does not run. A function without a return gives back undefined.
Default parameter values
You can give a parameter a default value that is used when the argument is missing.
function deliveryFee(distanceKm, ratePerKm = 30) {
return distanceKm * ratePerKm;
}
console.log(deliveryFee(10));
console.log(deliveryFee(10, 45));300 450
Function expressions
A function can also be stored in a variable. This is called a function expression.
const square = function (x) {
return x * x;
};
Functions in JavaScript are values, just like numbers and strings. You can store them, pass them to other functions, and return them from functions.
Arrow functions
Arrow functions are a shorter syntax for function expressions, and they are everywhere in modern JavaScript.
const square = (x) => {
return x * x;
};
// When the body is a single expression, drop the braces and return:
const cube = (x) => x * x * x;
// One parameter? The brackets are optional:
const double = n => n * 2;
// No parameters needs empty brackets:
const today = () => "Monday";
console.log(square(4), cube(3), double(21), today());16 27 42 Monday
With the short form, the expression after => is returned automatically. If you add curly braces, you must write return yourself.
this keyword. That matters inside objects and classes, which you will see in Objects. For simple calculations and callbacks, they behave the same.Functions as arguments (callbacks)
Because functions are values, you can pass one function into another. The function passed in is called a callback.
function applyToPrice(price, rule) {
return rule(price);
}
const halfPrice = (p) => p / 2;
const addDelivery = (p) => p + 200;
console.log(applyToPrice(1000, halfPrice));
console.log(applyToPrice(1000, addDelivery));500 1200
Callbacks are the idea behind array methods like map and filter (Array Methods), events (Events) and timers (Async JavaScript).
Scope
Variables declared inside a function exist only inside it. Code outside cannot see them. A function can, however, read variables from the code surrounding it.
const shop = "Duka la Mama";
function receipt(amount) {
const message = `${shop}: received KES ${amount}`;
return message;
}
console.log(receipt(250));
console.log(typeof message);Duka la Mama: received KES 250 undefined
Hoisting
Function declarations are hoisted: you can call them before the line where they are written. Function expressions and arrow functions stored in const cannot be used before their line.
console.log(triple(5));
function triple(n) {
return n * 3;
}15
Rest parameters
Put ... before the last parameter to collect any number of arguments into an array.
function sum(...numbers) {
let total = 0;
for (const n of numbers) total += n;
return total;
}
console.log(sum(100, 200));
console.log(sum(50, 50, 50, 50));300 200
Complete the function so it sends back the result.
function area(width, height) {
width * height;
}Write the arrow function that adds one to a number.
const addOne = (n) n + 1;
SKOPE