Last updated
JavaScript Functions
Definition: A function is a named, reusable block of code. Define it once, then call it whenever you need it — keeping code organised and avoiding repetition.
Example 1 — define and call
function greet() {
console.log("Hello!");
}
greet(); // call it
greet(); // call again
Example 2 — parameters (inputs)
function greet(name) {
console.log("Hello, " + name);
}
greet("Sam");
greet("Alex");
Example 3 — returning a value
function add(a, b) {
return a + b;
}
let result = add(3, 4);
console.log(result);
console.log(add(10, 20));
Example 4 — arrow functions (modern short form)
const add = (a, b) => a + b; const square = x => x * x; console.log(add(10, 5)); console.log(square(6));
Example 5 — a small useful function
function isEven(n) {
return n % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(7)); // false
💡 Tip: a good function does one clear job and has a descriptive name like calculateTotal.
Try it Yourself
Output
Ad · responsive