JavaScript functions matters once your pages get past the basics. Reusable blocks of code that perform a task. If variables hold data, functions do things with it.
What is a function?
A function is a set of instructions that performs a task or calculates a value. Write it once, call it whenever you need that task done.
Why use functions?
Without functions, you repeat the same code in multiple places. That is tedious and hard to maintain. A function puts the logic in one spot – call it, and the task runs without duplicating code.
Anatomy of a function
A typical JavaScript function has:
- The
functionkeyword. - A name.
- Parameters in parentheses, separated by commas.
- Instructions inside curly braces
{ }.
Example:
function sayHello() {
console.log("Hello, JavaScript!");
}
sayHello prints Hello, JavaScript! to the console.
Calling a function
Defining a function does not run it. You need to call (or invoke) it:
sayHello(); // Calls the function and prints "Hello, JavaScript!"
Parameters and arguments
Parameters are placeholders in the function definition. Arguments are the actual values you pass when calling it.
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Outputs: Hello, Alice!
greet("Bob"); // Outputs: Hello, Bob!
Here name is the parameter. "Alice" and "Bob" are the arguments.
Return values
Functions can send a value back with return.
Example:
function sum(a, b) {
return a + b;
}
let result = sum(5, 7);
console.log(result); // Outputs: 12
Local scope
Variables declared inside a function are not visible outside it. They have local scope.
Example:
function multiply(x, y) {
let product = x * y;
return product;
}
console.log(multiply(3, 4)); // Outputs: 12
// console.log(product); // Uncaught ReferenceError: product is not defined
Arrow functions
ES6 added arrow functions – a shorter syntax, especially for small functions.
Example:
const add = (a, b) => a + b;
console.log(add(10, 5)); // Outputs: 15
Callbacks and higher-order functions
You can pass a function as an argument to another function. That passed function is a callback. A function that takes or returns another function is a higher-order function.
Example:
function processUserInput(callback) {
let name = prompt('Please enter your name.');
callback(name);
}
processUserInput((name) => {
console.log('Hello ' + name);
});
Functions organise your code and keep it reusable. Write a few of your own before moving on to control structures.

