Beginner · JavaScript basics · topic 22 of 64 · 30 min
Functions
Explanation
Why functions?
If you calculate GST in ten places and the rate changes, you must fix ten places. Put the calculation in one function, and you fix it once. Functions also give a name to an idea, which makes code easier to read.
Declaring and calling
function withGst(price, rate) {
return price + (price * rate) / 100;
}
console.log(withGst(1000, 18)); // 1180
console.log(withGst(500, 5)); // 525Parameters are the names in the brackets when you write the function. Arguments are the real values you pass when you call it. return sends a value back and ends the function at once. A function without return gives back undefined.
Default parameters
function greet(name = 'Guest') {
return `Namaste, ${name}!`;
}
console.log(greet('Ravi')); // 'Namaste, Ravi!'
console.log(greet()); // 'Namaste, Guest!'Arrow functions
An arrow function is a shorter way to write a function, very common in modern code. If the body is a single expression, you can skip the curly braces and the word return.
const square = (n) => n * n;
const add = (a, b) => {
const sum = a + b;
return sum;
};
console.log(square(4), add(2, 3)); // 16 5Functions are values
You can store a function in a variable and pass it to another function. A function passed in this way is called a callback. You will use callbacks with array methods and events: "when the button is clicked, call this function".
Scope
Scope is where a variable can be used. A variable made with let or const inside a function or inside { } exists only there. This keeps functions independent: a total inside one function does not clash with a total in another.
Watch the lesson
Functions · 1/6
A function is a named set of steps you can use again and again.
Prefer a video by a teacher? Find free videos on “javascript functions arrow functions parameters return beginners” on YouTube ↗
In real life: Calculating a bill with GST
A billing page for a small electronics shop uses one function, withGst(price, rate), everywhere it shows a final price: the product page, the cart and the invoice. When a product moves to a different GST slab, only the rate passed in changes, and every page stays correct.
Practice (0/3 done)
Write a function withGst(price, rate) that returns the price plus GST at the given percent rate. withGst(1000, 18) returns 1180.
Write an arrow function called greet that takes a name with the default value "Guest" and returns "Namaste, <name>!". greet("Meena") returns "Namaste, Meena!" and greet() returns "Namaste, Guest!".
Write a function applyToAll(numbers, fn) that returns a new array where fn has been called on every number. applyToAll([1, 2, 3], (n) => n * 10) returns [10, 20, 30]. (Here fn is a callback.)
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.