Functions, Scope and Closures · Lesson 9 of 40
JavaScript Functions and Arrow Functions
A function is a reusable block of code with a name, inputs (parameters) and an output (a return value). Functions are the most important building block in JavaScript: event handlers, API calls, array methods and React components are all functions. In JavaScript functions are also values – you can store them in variables, pass them to other functions and return them.
In this lesson
- Declarations, expressions and arrow functions
- Parameters: defaults, rest and the arguments you pass
- Return values and early returns
- Function hoisting and pure functions
Three ways to create a function
// 1. Function declaration
function addGst(amount) {
return amount * 1.18;
}
// 2. Function expression – a function stored in a variable
const discount = function (amount, percent) {
return amount - (amount * percent) / 100;
};
// 3. Arrow function – short syntax, the modern default for small functions
const formatInr = (amount) => `₹${amount.toFixed(2)}`;
console.log(formatInr(addGst(discount(1000, 10))));
₹1062.00
Arrow function syntax
const square = n => n * n; // one parameter: brackets optional
const add = (a, b) => a + b; // expression body: returned automatically
const greet = () => "Hello!"; // no parameters
const makeUser = (name) => ({ name, active: true }); // return an object: wrap in ()
const describe = (n) => { // block body: needs an explicit return
const kind = n % 2 === 0 ? "even" : "odd";
return `${n} is ${kind}`;
};
console.log(square(9), add(2, 3), greet());
console.log(makeUser("Asha"));
console.log(describe(7));
81 5 Hello!
{ name: 'Asha', active: true }
7 is oddCommon mistake: braces without return
const add = (a, b) => { a + b }; returns undefined – braces make a block body, so you must write return. Arrow functions also have no this of their own, which matters for object methods (chapter 8).
Parameters
function createOrder(item, qty = 1, ...notes) {
return { item, qty, notes };
}
console.log(createOrder("Pen"));
console.log(createOrder("Notebook", 3, "gift wrap", "after 6pm"));
console.log(createOrder("Bag", undefined)); // undefined triggers the default
const max = Math.max(...[4, 19, 7]); // spread an array into arguments
console.log(max);
{ item: 'Pen', qty: 1, notes: [] }
{ item: 'Notebook', qty: 3, notes: [ 'gift wrap', 'after 6pm' ] }
{ item: 'Bag', qty: 1, notes: [] }
19- Default parameters (
qty = 1) apply when the argument is missing orundefined(but notnull). - Rest parameters (
...notes) collect the remaining arguments into a real array. They must come last. - Passing extra arguments is allowed (ignored); passing fewer leaves the missing ones
undefined.
For functions with many options, accept a single object and destructure it – callers can then pass options in any order:
function sendEmail({ to, subject = "(no subject)", urgent = false }) {
return `${urgent ? "[URGENT] " : ""}${subject} → ${to}`;
}
console.log(sendEmail({ to: "hr@example.com", urgent: true, subject: "Offer letter" }));
[URGENT] Offer letter → hr@example.com
Return values
return ends the function immediately and hands back a value. A function without return returns undefined. To return several values, return an object or an array:
function stats(nums) {
if (nums.length === 0) return null; // early return
const total = nums.reduce((a, b) => a + b, 0);
return { min: Math.min(...nums), max: Math.max(...nums), avg: total / nums.length };
}
const { min, max: highest, avg } = stats([12, 40, 8, 20]);
console.log(min, highest, avg);
console.log(stats([]));
function logOnly(msg) { console.log(msg); }
console.log(logOnly("hi"));
8 40 20 null hi undefined
Hoisting: declarations vs expressions
console.log(double(4)); // works: declarations are hoisted whole
function double(n) { return n * 2; }
try {
console.log(triple(4)); // const is in the temporal dead zone
} catch (e) {
console.log(e.name + ": " + e.message);
}
const triple = (n) => n * 3;
8 ReferenceError: Cannot access 'triple' before initialization
| Declaration | Expression / arrow | |
|---|---|---|
| Call before definition | yes (hoisted) | no (TDZ for const/let) |
Own this and arguments | yes | expression: yes · arrow: no |
| Typical use | top-level named helpers | callbacks, short utilities |
Pure functions
A pure function returns the same output for the same input and changes nothing outside itself. Pure functions are easy to test and reason about – keep most of your logic pure and isolate side effects (DOM updates, network calls, logging).
// Impure: changes the array passed in
function addItemImpure(cart, item) { cart.push(item); return cart; }
// Pure: returns a new array
const addItem = (cart, item) => [...cart, item];
const cart = ["rice"];
const newCart = addItem(cart, "dal");
console.log(cart, newCart);
[ 'rice' ] [ 'rice', 'dal' ]
Practice
Try it yourself
Write an arrow function
initials(fullName)that returns "A.K." for "Asha Kumari".Show solution
const initials = (fullName) => fullName.split(" ").map((w) => w[0].toUpperCase() + ".").join(""); console.log(initials("Asha Kumari"), initials("ravi shankar prasad"));A.K. R.S.P.
Write
sum(...nums)that adds any number of arguments.Show solution
const sum = (...nums) => nums.reduce((a, b) => a + b, 0); console.log(sum(), sum(5), sum(1, 2, 3, 4));0 5 10
Quick check
What does const f = () => { 42 } return?
undefined – a block body needs return 42.
Does a default parameter apply when you pass null?
No, only for a missing argument or undefined.
Can you call a function declaration before it appears in the file?
Yes – declarations are hoisted with their body.
Summary
- Functions are values: declarations, expressions and arrows all create them.
- Use defaults, rest parameters and an options object for flexible signatures.
- Declarations are hoisted; prefer small pure functions and isolate side effects.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.