A function in JavaScript is a reusable block of code designed to perform a specific task.
You can define a function once and use (call) it many times — this makes your code cleaner, shorter, and easier to manage.
function functionName() {
// code to run
}
Calling a function
functionName();
function sayHello() {
console.log("Hello, welcome to Learn2Kode!");
}
sayHello(); // calling the function
Parameters allow you to send values into a function.
function greet(name) {
console.log("Hello " + name);
}
greet("Mani");
greet("John");
Functions can return a value using return.
function add(a, b) {
return a + b;
}
let total = add(10, 5);
console.log(total); // 15
If a value is not provided, JavaScript uses the default.
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest
greet("learn2kode"); // Hello Mani
A function can be stored in a variable.
const multiply = function (x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20
A shorter way to write functions.
const add = (a, b) => {
return a + b;
};
console.log(add(3, 7)); // 10
If the function has only one line:
const square = n => n * n;
console.log(square(5)); // 25
A function with no name, often used in event listeners.
setTimeout(function () {
console.log("This runs after 2 seconds");
}, 2000);
Passing a function as a parameter to another function.
function printMessage() {
console.log("Hello from callback");
}
function executeCallback(callback) {
callback();
}
executeCallback(printMessage);
| Type | Description | Example |
|---|---|---|
| Function Declaration | Standard way to define functions | function greet() {} |
| Function Expression | Function stored in a variable | const x = function() {} |
| Arrow Function | Short ES6 function syntax | const x = () => {} |
| Callback Function | Function passed into another function | fn(() => {}) |