Function Basics
Learn to create and use functions in JavaScript with traditional syntax.
Functions are reusable blocks of code that perform specific tasks. They are fundamental to organizing your code and avoiding repetition. JavaScript offers several ways to define functions, but understanding the traditional function declaration and expression syntax is essential before moving to modern arrow functions. This exercise teaches you to create, call, and work with function parameters and return values.
📚 Concepts & Theory
Function Declaration:
function greet(name) {
return "Hello, " + name + "!";
}
let message = greet("Alice"); // "Hello, Alice!"
Function Expression:
const add = function(a, b) {
return a + b;
};
let sum = add(5, 3); // 8
Parameters and Arguments:
function multiply(x, y) { // x and y are parameters
return x * y;
}
multiply(4, 5); // 4 and 5 are arguments
Default Parameters:
function greet(name = "Guest") {
return "Hello, " + name;
}
greet(); // "Hello, Guest"
greet("Bob"); // "Hello, Bob"
Multiple Returns:
function checkAge(age) {
if (age >= 18) {
return "Adult";
}
return "Minor";
}
No Return Value:
function logMessage(msg) {
console.log(msg);
// Returns undefined implicitly
} 🎯 Your Challenge
Create a function called `calculateArea` that takes two parameters: `width` and `height`. The function should return the area (width multiplied by height). Then call the function with width 5 and height 10, storing the result in a variable called `rectangleArea`.
📝 Starter Code
// Create the function
function calculateArea(width, height) {
// Return the area
}
// Call the function
let rectangleArea =
- Use return to send back a value
- Parameters are defined in the function declaration
- Arguments are passed when calling the function
- Multiply with the * operator
Solution
function calculateArea(width, height) {
return width * height;
}
let rectangleArea = calculateArea(5, 10);
Explanation
We define a function that takes width and height as parameters and returns their product. When we call calculateArea(5, 10), JavaScript substitutes 5 for width and 10 for height, calculates 5 * 10 = 50, and returns that value which gets stored in rectangleArea.
⚠️ Common Mistakes to Avoid
- Forgetting the return statement
- Forgetting parentheses when calling the function
- Using wrong number of arguments
- Confusing parameters with arguments