A function is a reusable recipe: a named block of code that you write once and run whenever you need it. You give it some ingredients (inputs), it does its job, and it hands back a result (output).
Functions are the most important building block in JavaScript. They stop you repeating the same code in several places, they give a clear name to each task, and they let you test one small piece at a time. Every real app is made of many small functions working together.
Declaring and calling a function
function greet() {
console.log("Hello!");
}
greet(); // call it
greet(); // and againWriting a function, called declaring it, doesn't run it. Calling it, by writing its name followed by (), does. You can call the same function as many times as you like.
Forgetting the brackets is a common slip. greet on its own refers to the function without running it, so nothing happens.
Parameters and arguments
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada"); // Hello, Ada!
greet("Linus"); // Hello, Linus!nameis a parameter, a placeholder in the function's definition."Ada"is an argument, the real value you pass in when calling it.- Separate several parameters with commas:
function add(a, b). - Missing arguments become
undefined. Give a default value with=:function greet(name = "friend").
Parameters are what make a function reusable. The same function can greet anyone, add any two numbers or format any price.
return: sending a result back
function add(a, b) {
return a + b;
}
const total = add(2, 3); // 5returnsends a value back to the place where the function was called.- It also ends the function immediately, so code after it doesn't run.
- A function without
returngives backundefined.
Printing with console.log and returning are different. Logging shows a value to you in the console; returning hands it to your code so you can store it, compare it or pass it to another function.
Function expressions
Functions are values, so you can store them in variables:
const square = function (n) {
return n * n;
};This works like a function declaration, with one difference: a declared function can be called before the line where it's written, but a function stored in a variable can't. The next lesson covers the shorter arrow functions.
JavaScript Functions Syntax
Function syntax
function name(param1, param2 = defaultValue) {
// body
return result;
}
const result = name(arg1, arg2);JavaScript Functions Summary
- A function is a named, reusable block of code.
- Declaring a function defines it; calling it with
()runs it. - Parameters are placeholders; arguments are the values passed in.
returnsends a result back and ends the function.- Keep functions small, focused and clearly named.
JavaScript Functions Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Your first functions
function sayHi() {
console.log("Hi there! 👋");
}
function greet(name, emoji = "🙂") {
console.log(`Hello, ${name} ${emoji}`);
}
sayHi();
greet("Priya", "🎉");
greet("Tom");Line-by-line explanation
- Lines 1 to 3A function with no parameters.
- Line 5Two parameters; the second has a default value.
- Line 9Calling runs the body.
- Lines 10 to 11Different arguments, different output. Tom gets the default emoji.
Returning values
function celsiusToFahrenheit(c) {
return c * 9 / 5 + 32;
}
function isFreezing(c) {
return c <= 0;
}
const today = 18;
const f = celsiusToFahrenheit(today);
console.log(`${today}°C is ${f}°F`);
console.log("Freezing?", isFreezing(today));
console.log("Boiling point:", celsiusToFahrenheit(100));Line-by-line explanation
- Line 2
returnhands the result back. - Line 6Functions that answer yes/no questions often start with
is/has. - Line 10Store a function's result in a variable.
- Line 14Or use it directly inside another expression.
Early return and reuse
function shippingCost(total) {
if (total >= 50) {
return 0;
}
return 4.99;
}
function checkoutTotal(items) {
let sum = 0;
for (const price of items) sum += price;
return sum + shippingCost(sum);
}
console.log(checkoutTotal([20, 15]));
console.log(checkoutTotal([30, 25]));Line-by-line explanation
- Lines 2 to 4Return early. Once
return 0runs, the function ends. - Lines 8 to 12One function calls another. Small pieces combine into bigger ones.
- Lines 14 to 1535 + 4.99, and 55 + 0 (no delivery charge).
Common JavaScript Functions Mistakes
Forgetting the brackets
function roll() { return Math.ceil(Math.random() * 6); }
console.log(roll); // prints the function itselfconsole.log(roll()); // calls it and prints the resultLogging instead of returning
function double(n) {
console.log(n * 2);
}
const result = double(4) + 1; // NaN, because double returned undefinedfunction double(n) {
return n * 2;
}
const result = double(4) + 1; // 9Code after return
function getPrice() {
return 10;
console.log("Never runs");
}function getPrice() {
console.log("Getting price");
return 10;
}JavaScript Functions in Real Projects
Functions everywhere
formatDate(date), addToCart(product), validateEmail(text) and calculateTax(amount) are typical: real codebases are made of thousands of small, well-named functions. Libraries you'll use later, such as React, are largely a way of organising functions.
JavaScript Functions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the function so it returns the area of a rectangle.
area(width, height) {
width * height;
}
console.log(area(3, 4)); // 12
function and send the result back with return.What does this print?
function add(a, b = 10) {
return a + b;
}
console.log(add(5), add(5, 1));What does this print?
function shout(word) {
console.log(word.toUpperCase());
}
const result = shout("hey");
console.log(result);getInitials("Grace Hopper") should return "GH". Fix the function.
function getInitials(fullName) {
const parts = fullName.split(" ");
const initials = parts[0][0] + parts[1][0];
console.log(initials);
}
console.log(getInitials("Grace Hopper"));- getInitials returns "GH"
- Works for another name
JavaScript Functions Quiz
4 questions to check what you learned.
How do you call a function named
start?- call start
- start
- start()
- function start()
What's the difference between a parameter and an argument?
- There is no difference
- Arguments are in the definition
- Parameters are always numbers
- Parameters are placeholders in the definition; arguments are the actual values passed in
What does a function return if it has no
returnstatement?- undefined
- null
- 0
- An error
What happens to code written after
returnin the same block?- It runs after the return
- It never runs
- It runs before the return
- It causes a syntax error
JavaScript Functions Challenge
Write a price formatter
Write a function formatPrice(amount, currency = "£") that:
- Returns the currency symbol followed by the amount with 2 decimals
formatPrice(5)→"£5.00"formatPrice(12.5, "$")→"$12.50"
Then log both results.
- formatPrice(5) is "£5.00"
- formatPrice(12.5, "$") is "$12.50"
- formatPrice(0.1, "€") is "€0.10"
- It returns (not just logs)