JavaScript Functions
1. What is a Function?
A function in JavaScript is a block of code designed to perform a particular task or calculation. It is reusable and can be executed whenever needed by calling or invoking it. Functions help in organizing code into manageable pieces and enable code reuse.
Think of a function as a named recipe: it defines steps (code), and you can follow (call) the recipe whenever you want without rewriting it.
2. Why Use Functions?
- Reusability: Write a piece of logic once, reuse it anywhere.
- Modularity: Break complex problems into smaller functions.
- Maintainability: Fix or update code in one place.
- Readability: Named functions explain the purpose of code blocks.
- Abstraction: Hide complex details and expose simple interfaces.
- Testability: Functions can be tested individually.
3. How to Define and Use Functions
3.1 Function Declaration
Defined using the function keyword with a name and optional parameters. These functions are hoisted (can be called before they appear).
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Hello, Alice!
3.2 Function Invocation
Calling a function by using its name followed by parentheses and any required arguments:
greet("Bob"); // Hello, Bob!
3.3 Returning Values
Functions can send back a result to the caller using the return statement:
function add(a, b) {
return a + b;
}
let sum = add(5, 7);
console.log(sum); // 12
4. Function Parameters & Arguments
Parameters are placeholders in a function definition representing values it expects. Arguments are actual values passed when calling the function.
function multiply(x, y) { // x and y are parameters
return x * y;
}
multiply(4, 6); // 4 and 6 are arguments
Functions can have default parameters to handle missing arguments:
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Hello, Guest!
5. Types of Functions
5.1 Function Declaration (Named Function)
Traditional, hoisted functions with a name.
function sayHi() {
console.log("Hi!");
}
sayHi();
5.2 Function Expression
Function stored in a variable. Not hoisted, so declare before use.
const greet = function(name) {
console.log("Hello, " + name);
};
greet("Charlie");
5.3 Arrow Functions
Introduced in ES6, shorter syntax, no own this or arguments. Ideal for callbacks and concise functions.
const square = (n) => n * n;
console.log(square(5)); // 25
5.4 Anonymous Functions
Functions without names, often used inline or as callbacks:
setTimeout(function() {
console.log("Delayed hello!");
}, 1000);
5.5 Immediately Invoked Function Expressions (IIFE)
Runs immediately after definition. Useful for creating isolated scopes.
(function() {
console.log("IIFE running!");
})();
5.6 Async Functions
Use the async keyword to work with asynchronous code more cleanly using await.
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
5.7 Recursive Functions
Functions that call themselves to solve problems by breaking them down.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
6. Function Scope and Closures (Brief)
Functions create their own scope. Variables declared inside a function are not accessible outside it.
function testScope() {
let secret = "hidden";
console.log(secret);
}
testScope(); // "hidden"
console.log(secret); // ReferenceError: secret is not defined
Closures happen when a function “remembers” the variables from its outer scope even after that scope has finished execution.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
}
}
const counter = outer();
counter(); // 1
counter(); // 2
7. Best Practices When Using Functions
- Give functions descriptive names reflecting their purpose.
- Keep functions small and focused on one task.
- Use parameters to make functions flexible and reusable.
- Return values instead of printing inside functions for better reusability.
- Use arrow functions for concise callbacks.
- Handle errors inside functions or let them propagate sensibly.
- Use comments and documentation to clarify complex logic.
8. Assignments
- Write a function
greetUserthat accepts a name and prints a personalized greeting. - Create a function to calculate the factorial of a number using recursion.
- Write an arrow function
isEventhat returns true if a number is even. - Write a function that takes an array of numbers and returns the maximum number.
- Build an async function to fetch user data from a free API and print the user's name.
- Create an IIFE that logs "Hello, IIFE!" immediately.
- Write a function expression that converts Fahrenheit to Celsius.
- Create a function that accepts another function as a callback and calls it after 2 seconds.
- Write a function with default parameters that calculates the power of a number.
- Write a recursive function that calculates the nth Fibonacci number.