Functions group reusable code. You can pass inputs (parameters) and optionally return an output (result).
JavaScript Functions
1) Function Declaration
Standard way to define a function with a name.
function greet() {
console.log("Hello!");
}
greet(); // Hello!
2) Parameters & Return
Pass values into a function and return results.
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // 7
3) Function Expression
Assign an anonymous function to a variable.
const square = function(n) {
return n * n;
};
console.log(square(5)); // 25
4) Arrow Functions
Shorter syntax, introduced in ES6.
const multiply = (x, y) => x * y;
console.log(multiply(2, 3)); // 6
5) Default Parameters
Provide fallback values when no argument is passed.
function greetUser(name = 'Guest') {
console.log('Hello ' + name);
}
greetUser(); // Hello Guest
greetUser('Sonu'); // Hello Sonu
6) Rest Parameters
Use ... to collect multiple arguments into an array.
function sumAll(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sumAll(1, 2, 3, 4)); // 10
7) IIFE (Immediately Invoked Function Expression)
Executes immediately after definition. Useful for isolating scope.
(function() {
console.log("This runs instantly");
})();
Tip: Prefer arrow functions for short callbacks. Use regular
function when you need your own this context.