1. What is a Function?
A function is a reusable block of code designed to perform a particular task.
It can take inputs (parameters), do some work, and (optionally) return a value.
2. Ways to Define a Function
A. Function Declaration (Traditional)
function greet() {
console.log("Hello, world!");
greet(); // Output: Hello, world!
B. Function Expression (Anonymous Function)
const add = function(x, y) {
return x + y;
};
console.log(add(2, 3)); // Output: 5
C. Arrow Function (ES6)
const multiply = (a, b) => a * b;
console.log(multiply(3, 4)); // Output: 12
// Single parameter, single-line:
const square = n => n * n;
console.log(square(5)); // Output: 25
3. Parameterized vs Non-Parameterized Functions
A. No-parameter Function
function sayHello() {
return "Hello!";
}
console.log(sayHello()); // Output: Hello!
B. Parameterized Function
function greetUser(name) {
return `Hello, ${name}!`;
console.log(greetUser("Vikas")); // Output: Hello, Vikas!
4. Default Parameters
function greet(name = "Guest") {
return `Hello, ${name}!`;
console.log(greet()); // Output: Hello, Guest!
5. Functions with Multiple Returns
Note:
A function can only return one value directly, but that value can be any type (including arrays or
objects to simulate multiple returns).
function stats(a, b) {
return {
sum: a + b,
diff: a - b,
prod: a * b
};
let result = stats(6, 2);
console.log(result.sum); // Output: 8
console.log(result.diff); // Output: 4
console.log(result.prod); // Output: 12
Or, return an array:
function minMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
let [min, max] = minMax([3, 8, 5, 1]);
console.log(min, max); // Output: 1 8
6. Callback Functions
A callback is a function passed as an argument to another function, to be executed later.
function processData(data, callback) {
console.log("Processing...");
callback(data);
processData([1,2,3], function(arr) {
console.log("Length:", arr.length);
});
// Output:
// Processing...
// Length: 3
Arrow function as callback:
let numbers = [10, 13, 24, 7, 16, 9];
numbers.forEach(num => {
if(num % 2 === 0) {
console.log(num + " is even");
});
7. Anonymous Functions
Functions without a name, usually used as values or callbacks.
setTimeout(function() {
console.log("Hello after 2 seconds!");
}, 2000);
8. Returning Complex Types
Functions can return anything: primitives, objects, arrays, other functions.
function makeAdder(x) {
return function(y) {
return x + y;
};
const add5 = makeAdder(5);
console.log(add5(10)); // Output: 15
This is called a “higher-order function”.
9. The return Statement
Ends the function immediately and outputs the specified value.
If no return, the function returns undefined.
Can return:
o Nothing (undefined)
o Primitive (number, string, etc.)
o Array
o Object
o Another function
Examples of Different Returns:
function noReturn() {
console.log("No explicit return");
console.log(noReturn()); // Output: No explicit return \n undefined
function returnArray() {
return [1, 2, 3];
console.log(returnArray()); // [1, 2, 3]
function returnObject() {
return {a: 10, b: 20};
console.log(returnObject()); // {a: 10, b: 20}
10. Immediately Invoked Function Expression (IIFE)
A function that runs as soon as it is defined.
(function(){
console.log("IIFE runs automatically!");
})(); // Output: IIFE runs automatically!
Quick Table: Types of Functions
Type Example
Declaration function fn() {}
Expression const fn = function() {}
Arrow const fn = () => {}
Anonymous setTimeout(function(){}, 1000)
Parameterized function fn(x) {}
No Parameter function fn() {}
Callback arr.map(x => x*x)
Returning Object/Array function fn() { return [1,2]; }
IIFE (function(){ ... })()
Exercises
1. Multiple Return Types:
Write a function that takes a list of numbers and returns an object with the properties: min,
max, and average.
2. Callback Practice:
Write a function calculate that takes two numbers and a callback.
o The callback should perform any operation (add, subtract, multiply, divide).
o Call calculate with different callbacks for each operation.
3. Arrow Functions and Array Processing:
Write an arrow function that takes an array of strings and returns a new array of all strings
that are longer than 4 characters, all in uppercase.
4. Default Parameters and Return Arrays:
Write a function that takes two parameters (start, end) and returns an array of all numbers
between them (inclusive).
If only one parameter is given, start from 1.
5. Functions Returning Functions:
Write a function makeMultiplier(factor) that returns a new function.
o This returned function takes a number and multiplies it by factor.
o Example: const double = makeMultiplier(2); double(5); // 10