Scalable Business for Startups
Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.
Chapter 7: Functions in JavaScript
Functions are one of the most powerful tools in JavaScript, allowing for modular and reusable code. We’ll cover various function types and explore their nuances with multiple examples.
7.1 What is a Function?
A function in JavaScript is a reusable set of statements designed to perform a specific task. By defining functions, we make our code modular, easier to debug, and easier to maintain.
Examples
1. Basic Function
function sayHello() {
console.log("Hello, World!");
}
sayHello(); // Output: Hello, World!
2. Function with Parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
3. Function with Return Value
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
4. Function without Parameters
function showTime() {
console.log("Current time: " + new Date().toLocaleTimeString());
}
showTime(); // Output: Current time: (depends on your time zone)
5. Function to Perform Calculation
function calculateRectangleArea(length, width) {
return length * width;
}
console.log(calculateRectangleArea(10, 5)); // Output: 50
7.2 Defining a Function
There are multiple ways to define a function in JavaScript: function declarations, function expressions, and arrow functions.
Function Declaration
1. Basic Declaration
function multiply(a, b) {
return a * b;
}
console.log(multiply(2, 3)); // Output: 6
2. Default Parameters
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
3. Conditional Function Execution
function isEven(num) {
if (num % 2 === 0) {
return true;
}
return false;
}
console.log(isEven(4)); // Output: true
console.log(isEven(3)); // Output: false
4. Factorial Calculation Using Declaration
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
5. Calculator Function
function calculator(a, b, operation) {
if (operation === "add") return a + b;
if (operation === "subtract") return a - b;
if (operation === "multiply") return a * b;
if (operation === "divide") return a / b;
return "Invalid operation";
}
console.log(calculator(10, 5, "add")); // Output: 15
7.3 Function Parameters and Arguments
Function parameters act as placeholders for values passed into the function, called arguments.
Examples
1. Basic Parameters and Arguments
function square(num) {
return num * num;
}
console.log(square(4)); // Output: 16
2. Multiple Parameters
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(1, 2, 3)); // Output: 6
3. Parameters with Default Values
function increment(value, step = 1) {
return value + step;
}
console.log(increment(5)); // Output: 6
console.log(increment(5, 3)); // Output: 8
4. Function with Missing Arguments
function subtract(a, b) {
return a - (b || 0);
}
console.log(subtract(10)); // Output: 10
5. Passing Functions as Arguments
function repeat(operation, times) {
for (let i = 0; i < times; i++) {
operation();
}
}
repeat(() => console.log("Hello!"), 3);
// Output: Hello! Hello! Hello!
7.4 Returning Values
The return
statement is used to return a value from a function.
Examples
1. Basic Return Value
function add(a, b) {
return a + b;
}
console.log(add(5, 7)); // Output: 12
2. Early Return
function checkAge(age) {
if (age < 18) return "Minor";
return "Adult";
}
console.log(checkAge(20)); // Output: Adult
3. Using Return in Conditional Logic
function compare(a, b) {
if (a > b) return a;
return b;
}
console.log(compare(10, 5)); // Output: 10
4. Return in Recursive Function
function countdown(num) {
if (num === 0) return;
console.log(num);
return countdown(num - 1);
}
countdown(5);
// Output: 5, 4, 3, 2, 1
5. Return Complex Object
function createUser(name, age) {
return { name: name, age: age, active: true };
}
console.log(createUser("Alice", 25));
// Output: { name: 'Alice', age: 25, active: true }
7.5 Anonymous Functions
Anonymous functions are functions without a name, often used as arguments or immediately invoked.
Examples
1. Function Expression (Anonymous)
const greet = function() {
console.log("Hello from anonymous function!");
};
greet(); // Output: Hello from anonymous function!
2. Anonymous Function in setTimeout
setTimeout(function() {
console.log("Anonymous function executed after delay");
}, 2000);
3. Immediately Invoked Anonymous Function
(function() {
console.log("IIFE executed");
})(); // Output: IIFE executed
4. Array Manipulation with Anonymous Function
let numbers = [1, 2, 3];
numbers.forEach(function(number) {
console.log(number * 2);
});
// Output: 2, 4, 6
5. Event Handler with Anonymous Function
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
7.6 Arrow Functions
Arrow functions provide a more concise syntax for writing function expressions and do not bind their own this
.
Examples
1. Basic Arrow Function
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
2. Arrow Function with No Parameters
const sayHi = () => console.log("Hi!");
sayHi(); // Output: Hi!
3. Arrow Function Returning an Object
const createUser = (name, age) => ({ name: name, age: age });
console.log(createUser("Alice", 25));
// Output: { name: 'Alice', age: 25 }
4. Arrow Function with Default Parameter
const multiply = (a, b = 1) => a * b;
console.log(multiply(5)); // Output: 5
5. Arrow Function with Implicit Return
const square = x => x * x;
console.log(square(4)); // Output: 16
7.7 Higher-Order Functions
Higher-order functions are functions that take other functions as arguments or return functions as their result.
Examples
1. Function that Returns Another Function
function outerFunction() {
return function innerFunction() {
console.log("Inner function executed");
};
}
const inner = outerFunction();
inner(); // Output: Inner function executed
2. Using Functions as Arguments
function operate(a, b, operation) {
return operation(a, b);
}
console.log(operate(5, 3, (x, y) => x - y)); // Output: 2
3. Array Method as Higher-Order Function
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
4. Using Filter with a Callback Function
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
5. Reducing an Array with a Callback Function
const total = numbers.reduce((sum, num) => sum + num, 0);
console.log(total); // Output: 10