Function declarations
Overview
A function is a named block of code you can run whenever you need it. Instead of repeating the same lines in several places, you write them once inside a function and call it by name. Functions keep your programs short, make each part easier to understand, and let you fix a bug in one place.
function greet(name) {
return `Hello, ${name}!`;
}
greet('Asha'); // 'Hello, Asha!'
greet('Ravi'); // 'Hello, Ravi!'Anatomy of a function
A function declaration has four parts:
- The
functionkeyword. - A name, which follows the same rules as variable names. By convention it’s a verb in camelCase:
calculateTotal,showMessage,isValid. - A list of parameters in brackets — local variables that receive the values you pass in. A function can have none:
function sayHi() { … }. - The body in curly braces: the statements that run each time the function is called.
Defining versus calling
Writing the declaration only defines the function; nothing inside it runs yet. To run it you call (or invoke) it by writing its name followed by brackets:
function sayHi() {
console.log('Hi!');
}
sayHi; // does nothing useful — this is the function itself, a value
sayHi(); // runs it → 'Hi!'Forgetting the brackets is a common slip. You’ll see later that referring to a function without calling it is useful — that’s how you pass functions to other functions.
Parameters and arguments
Parameters are the names in the function’s definition. Arguments are the values you pass when you call it. Each argument is copied into the matching parameter, by position:
function rectangleArea(width, height) {
return width * height;
}
rectangleArea(4, 3); // width = 4, height = 3 → 12You can give parameters a default:
function greet(name = 'friend') {
return `Hello, ${name}!`;
}
greet(); // 'Hello, friend!'The next-but-one topic, Parameters and arguments, goes much deeper.
Returning values
return ends the function and hands a value back to the caller, who can store it, print it or pass it on:
function addTax(price) {
return price * 1.18;
}
const total = addTax(100); // 118
console.log(addTax(50)); // 59
const both = addTax(addTax(100)); // the result of one call fed into anotherA function without return gives back undefined. That’s fine for functions that do something (show a message, save data) rather than calculate something.
function logTotal(total) {
console.log(`Total: ${total}`);
}
const result = logTotal(5); // logs 'Total: 5'; result is undefinedreturn stops the function
Any code after a return that runs is skipped. This lets you leave early:
function divide(a, b) {
if (b === 0) {
return 'Cannot divide by zero';
}
return a / b;
}A function can only return one value. To return several, return an object or an array:
function minMax(numbers) {
return { min: Math.min(...numbers), max: Math.max(...numbers) };
}
const { min, max } = minMax([3, 9, 1]); // min 1, max 9Local variables
Variables declared inside a function exist only while it runs, and only inside it. Each call gets a fresh set:
function countVowels(word) {
let count = 0; // local — starts at 0 on every call
for (const ch of word.toLowerCase()) {
if ('aeiou'.includes(ch)) count++;
}
return count;
}
countVowels('JavaScript'); // 3
console.log(count); // ReferenceError — count doesn't exist out hereFunctions can read variables from outside themselves (see Scope and hoisting), but a function that only uses its parameters and returns a result is easier to test and reuse.
Hoisting
Function declarations are moved to the top of their scope before the code runs, so this works:
sayHi();
function sayHi() {
console.log('Hi!');
}This lets you put the main logic at the top of a file and helper functions below it.
Function expressions
A function can also be created as a value and stored in a variable. This is a function expression:
const sayHi = function () {
console.log('Hi!');
};
sayHi();Function expressions aren’t hoisted. If you write
const sayHi = function () {}, you must define it before calling it.
Expressions are common when passing a function to another function, and they’re the basis of the shorter arrow functions in the next topic.
Writing good functions
- Do one job. If you need “and” to describe it (
validateAndSaveAndEmail), split it up. - Name it for what it does.
getUser,formatDate,isEmpty. Booleans read well withis/has/can. - Keep it short. A function you can read without scrolling is easier to trust.
- Prefer returning over printing.
returna result and let the caller decide whether to log it, show it or use it.
Write a function
Write a function fullName that takes a first and last name and returns them joined with a space. Then write isLongName(first, last) that uses fullName and returns true if the full name is longer than 12 characters.
function fullName(first, last) {
// your code here
}
function isLongName(first, last) {
// your code here
}function fullName(first, last) {
return `${first} ${last}`;
}
function isLongName(first, last) {
return fullName(first, last).length > 12;
}Summary
- A function declaration starts with
function name(params) { }. - Declaring a function doesn’t run it — calling it with
name()does. returnsends a value back and ends the function; without it the function returnsundefined.- Declarations are hoisted, so you can call them before they appear.
- Good functions do one job and are named with a verb.