7. Functions in JavaScript - Parameters, Return, and Arrow Functions
What Are Functions?
A function is a reusable block of code that performs a specific task. You can call it anytime you need that same logic again — instead of repeating yourself.
function greet() {
console.log("Hello, world!");
}
greet(); // Calls the functionThis defines a function named `greet` that logs a message, and then calls it using `greet()`. Easy, right?
Function Parameters
Functions can take **parameters** — placeholders for data you pass in when calling the function. These make functions dynamic and reusable.
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Ada"); // Output: Hello, Ada!Here, `name` is a parameter, and `"Ada"` is the argument we passed in.
Returning Values
Functions can return results using the `return` keyword. This sends data back to wherever the function was called.
function add(a, b) {
return a + b;
}
const result = add(5, 3);
console.log(result); // 8`return` exits the function and gives back a value — super useful for calculations or reusable logic.
Function Expressions
You can also create functions and store them inside variables. These are called **function expressions**.
const multiply = function (x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20Arrow Functions
ES6 introduced **arrow functions**, a shorter way to write functions. They’re clean and perfect for simple operations.
const square = (n) => {
return n * n;
};
console.log(square(6)); // 36If the function has just one expression, you can skip the braces `{}` and the `return` keyword.
const double = n => n * 2;
console.log(double(8)); // 16Default Parameters
You can give parameters default values, so they’re used if no argument is provided.
function greetUser(name = "friend") {
console.log("Hi, " + name + "!");
}
greetUser(); // Hi, friend!
greetUser("Nia"); // Hi, Nia!Mini Challenge
1. Write a function `sayBye` that takes a name and logs a goodbye message. 2. Create an arrow function `addThree` that takes a number and returns that number + 3. 3. Try using default parameters in one of them.
// Example:
function sayBye(name = "friend") {
console.log(`Goodbye, ${name}!`);
}
const addThree = num => num + 3;
sayBye("Ada"); // Goodbye, Ada!
console.log(addThree(7)); // 10Key Takeaway
Functions make your code reusable, flexible, and easier to maintain. Whether you’re creating simple helpers or complex logic, mastering them is key to writing clean JavaScript.