Introduction to Functions
Reusable blocks of code. The building blocks of every JavaScript program.
What Are Functions?
Named, reusable blocks of code that perform a specific task.
A function is like a recipe — you define it once, then use it whenever you need it.
Without functions
console.log("Hello, Alice");
console.log("Hello, Bob");
console.log("Hello, Charlie");
// Repeat for every name...With a function
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice");
greet("Bob");
greet("Charlie");Declaring Functions
The function keyword creates a function.
function functionName(parameters) {
// function body — code to execute
return result; // optional
}Anatomy of a function:
function greet(name) {
return "Hello, " + name;
}
// A function that adds two numbers:
function add(a, b) {
return a + b;
}
// A function with no parameters:
function sayHello() {
console.log("Hello!");
}
// A function with no return (returns undefined):
function logMessage(msg) {
console.log(msg);
// implicit: return undefined;
}Calling Functions
Defining a function doesn't run it. You must call it.
// Defining ≠ Running
function greet() {
console.log("Hello!");
}
// Nothing happens yet!
// We must CALL it:
greet(); // "Hello!" — NOW it runs
greet(); // "Hello!" — runs again
greet(); // "Hello!" — and again// Click to call the function:
Called 0 times
💡 The parentheses () after the name are what executethe function. Without them, you're just referencing the function object, not running it.
// Reference vs Call: console.log(greet); // [Function: greet] — the function itself console.log(greet()); // "Hello!" — calls it, logs the return value
Naming Functions
Good names make code self-documenting.
| Pattern | Examples |
|---|---|
| verb + noun | getUser, sendEmail, calculateTotal |
| is/has + adjective | isValid, hasPermission, isEmpty |
| handle + event | handleClick, handleSubmit |
| on + event | onLoad, onChange, onError |
✗ Bad names
function do()
function stuff()
function x(a, b)
function data()
✓ Good names
function processPayment()
function formatDate()
function add(a, b)
function fetchUserData()
Function Hoisting
Declarations are moved to the top of their scope.
// This works! Declaration is hoisted:
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
// JavaScript sees it as:
// function greet() { ... } ← moved to top
// greet(); ← then this runs💡 Only function declarations are hoisted. Function expressions and arrow functions are NOT — they behave like regular variables.
// This does NOT work:
sayHi(); // TypeError: sayHi is not a function
const sayHi = function() {
console.log("Hi!");
};Exercises
Test your understanding.
What does this return?
function add(a, b) {
return a + b;
}
add(3, 4);What is printed?
sayHi();
function sayHi() {
console.log("Hello");
}What does a function return if there's no return statement?
What is this called: function() {}?
Frequently Asked Questions
Common questions about functions.