Lesson 5: Functions in JavaScript
Functions are blocks of code designed to perform a specific task. They help in organizing code into reusable pieces, which makes code more modular and easier to maintain.
Defining Functions
1. Function Declaration
A function declaration defines a named function. The function can be called from anywhere in the code after the declaration.
function functionName(parameters) {
// Code to execute
}
Example of Function Declaration:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
2. Function Expression
A function expression creates a function and assigns it to a variable. The function can only be called after it is defined.
const functionName = function(parameters) {
// Code to execute
};
Example of Function Expression:
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
3. Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They are often used for short functions and do not have their own this context.
const functionName = (parameters) => {
// Code to execute
};
Example of Arrow Functions:
const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20
Function Parameters and Return Values
1. Parameters
Parameters are variables listed as part of a function definition. They act as placeholders for values that are passed into the function.
function greet(name, age) {
console.log("Hello, " + name + ". You are " + age + " years old.");
}
2. Return Values
The return statement ends function execution and specifies a value to be returned to the function caller.
function square(number) {
return number * number;
}
console.log(square(5)); // Output: 25
Assignment
Create a program that:
- Defines a function to calculate the factorial of a number.
- Defines a function to check if a number is prime.
- Uses an arrow function to find the maximum of three numbers.