Declaring and Calling Functions
A function gives a name to a piece of work so you can run it whenever you need it, instead of writing it out again.
Declaring a function stores the work under a name; calling it with brackets runs it. Naming the function and calling it are two separate things, and confusing them is a common early mistake.
EXERCISE
1Naming a Piece of Work
A function is a set of instructions with a name, written once and run as many times as you like.
Without functions, repeated work means repeated code, and repeated code means fixing the same bug in four places.
The problem:
console.log("=================");
console.log(" Welcome, Ada");
console.log("=================");
console.log("=================");
console.log(" Welcome, Grace");
console.log("=================");
// Change the banner style and you now edit it twice.
The fix:
function welcome(name) {
console.log("=================");
console.log(` Welcome, ${name}`);
console.log("=================");
}
welcome("Ada");
welcome("Grace");
// One definition. Two uses. One place to change it.
The anatomy:
function greet(name) {
console.log(`Hello, ${name}`);
}
// ^keyword ^name ^parameter
// { } <- the body
greet("Ada"); // the call. The brackets are what runs it.
Declaring and calling are different things:
function sayHi() {
console.log("Hi");
}
sayHi; // nothing happens. This is the function itself, as a value.
sayHi(); // Hi <- the brackets run it
console.log(sayHi); // [Function: sayHi]
console.log(sayHi()); // Hi, then undefined (what it returned)
Pro Tip: The brackets are the call. A function name on its own is just a value, like a number sitting in a variable, and JavaScript will let you write it without complaint. Forgetting the brackets is one of the quietest bugs there is: nothing happens, nothing errors, and the line looks correct.
EXERCISE
2Why Functions Are Worth the Trouble
The obvious benefit is avoiding repetition, and the larger benefit is that a good name lets you stop thinking about the details.
Naming hides detail, which is the real prize:
// Without a name, you have to read the arithmetic to know what it is:
const t = (p * q) + ((p * q) * 0.18) - d;
// With names, you read the intent and trust the detail:
function calculateTotal(price, quantity, discount) {
const subtotal = price * quantity;
const tax = subtotal * 0.18;
return subtotal + tax - discount;
}
const total = calculateTotal(250, 3, 50);
console.log(total); // 785
One place to fix, one place to test:
function isValidEmail(value) {
return value.includes("@") && value.includes(".");
}
console.log(isValidEmail("ada@example.com")); // true
console.log(isValidEmail("nope")); // false
// When the rule changes, it changes here and nowhere else.
// And you can check it in the console in two seconds.
Small functions compose into larger ones:
function toPaise(rupees) {
return Math.round(rupees * 100);
}
function formatPaise(paise) {
return `Rs ${(paise / 100).toFixed(2)}`;
}
function priceLabel(rupees) {
return formatPaise(toPaise(rupees));
}
console.log(priceLabel(19.995)); // Rs 20.00
A function should do one thing that you can name honestly. When the best name you can find is handleStuff or processData, the function is doing several things and wants splitting. The name is not decoration, it is a test of whether you understand what the code does.
EXERCISE
3Three Ways to Create a Function
The same work can be written as a declaration, an expression or an arrow, and the differences matter more than the syntax suggests.
A declaration, which is what you have been writing:
function double(n) {
return n * 2;
}
console.log(double(5)); // 10
An expression, which stores a function in a variable:
const triple = function (n) {
return n * 3;
};
console.log(triple(5)); // 15
// Note the semicolon. This is an assignment, so it ends like one.
An arrow function, the short modern form:
const quadruple = (n) => {
return n * 4;
};
console.log(quadruple(5)); // 20
The one difference you will notice first:
console.log(early(2)); // 4 works, even though it is defined below
function early(n) {
return n * 2;
}
console.log(late(2)); // ReferenceError: Cannot access 'late' before initialization
const late = function (n) {
return n * 2;
};
A declaration is available everywhere in its scope, including above the line that defines it. A function stored in a const is not available until that line runs. The lesson on hoisting explains why.
All three create a function, and the function itself behaves identically once it exists. What differs is when it comes into existence and, for arrows, what this means inside it. Start with declarations for standalone functions and arrows for short ones passed to other functions, which is the split most real codebases use.
