Function Declaration and Expressions
Functions are fundamental building blocks in JavaScript, allowing you to create reusable blocks of code that perform specific tasks. In this lesson, you will learn about function declarations, function expressions, and the differences between them.
1. What is a Function?
A function is a block of code designed to perform a specific task. Functions are useful for:
- Breaking down complex problems into smaller, manageable parts.
- Avoiding code repetition.
- Making code more organized and readable.
Functions can accept input (parameters) and return output, making them versatile tools in any JavaScript program.
2. Function Declaration
A function declaration defines a function with a specified name and can be called from anywhere in the scope where it is defined. This type of function is hoisted, meaning it can be used before its definition in the code.
Syntax:
function functionName(parameters) {
// Code to execute
}
- functionName: The name you assign to the function, used to call the function.
- parameters: Optional values that the function can take as input.
Example of a Function Declaration:
function greet(name) {
console.log("Hello, " + name + "!");
}
// Calling the function
greet("Alice"); // Outputs: Hello, Alice!
3. Function Expressions
A function expression defines a function and assigns it to a variable. Unlike function declarations, function expressions are not hoisted and cannot be called before they are defined in the code.
Syntax:
const variableName = function(parameters) {
// Code to execute
};
- variableName: The name of the variable to which the function is assigned.
- function(parameters): The function itself, without a name (also known as an anonymous function).
Example of a Function Expression:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
// Calling the function
greet("Bob"); // Outputs: Hello, Bob!
4. Differences Between Function Declarations and Expressions
Feature | Function Declaration | Function Expression |
---|---|---|
Syntax | function greet() {} |
const greet = function() {} |
Hoisting | Hoisted (can be called before definition) | Not hoisted (must be defined before calling) |
Naming | Must have a name | Can be anonymous |
Use Cases | Preferred for general functions | Useful for inline or immediate functions |
5. Parameters and Arguments
Functions can accept input values, known as parameters. When calling a function, the values passed are called arguments. Parameters allow functions to be more flexible by accepting different inputs.
Example with Parameters:
function add(a, b) {
return a + b;
}
let result = add(5, 3); // Outputs: 8
In this example, a
and b
are parameters, while 5
and 3
are arguments provided during the function call.
6. Returning Values from Functions
Functions can return a value using the return
statement. When a function executes a return
statement, it immediately stops and outputs the specified value. This allows functions to send results back to the caller.
Example:
function multiply(x, y) {
return x * y;
}
let product = multiply(4, 5); // Returns 20
console.log(product); // Outputs: 20
If a function does not include a return
statement, it returns undefined
by default.
7. Anonymous Functions
An anonymous function is a function without a name. It is often used in situations where functions are passed as arguments or assigned to variables. Function expressions are commonly used to define anonymous functions.
Example of Anonymous Function:
const sayHi = function() {
console.log("Hi!");
};
sayHi(); // Outputs: Hi!
Anonymous functions are also useful in situations where functions are used as arguments, such as in array methods (map
, filter
, etc.) and event handlers.
8. Named Function Expressions
In a function expression, you can optionally give the function a name. This name is only accessible inside the function itself, which can be useful for recursion or debugging.
Example of Named Function Expression:
const factorial = function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1);
};
console.log(factorial(5)); // Outputs: 120
Here, fact
is the name of the function, but it is only accessible inside the function body.
9. IIFE (Immediately Invoked Function Expressions)
An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed immediately. IIFEs are useful for creating a private scope, avoiding global variable pollution.
Syntax:
(function() {
// Code to execute immediately
})();
Example of IIFE:
(function() {
console.log("This function runs immediately!");
})();
Output:
This function runs immediately!
10. Practical Use Cases for Functions
- Reusable Code: Define functions once and use them multiple times.
- Organizing Code: Break down large problems into smaller, logical units.
- Callbacks and Higher-Order Functions: Pass functions as arguments to other functions.
- Encapsulating Logic: Create modular and maintainable code structures.
11. Coding Exercises
Now it’s time to practice! In a JavaScript file called functionsPractice.js
, implement the following exercises:
- Write a function named
greetUser
that accepts aname
parameter and prints a greeting (e.g., "Hello, name!"). - Create a function expression called
subtract
that takes two arguments and returns their difference. - Implement an IIFE that logs "Executed immediately!".
- Write a function
isEven
that takes a number as input and returnstrue
if the number is even andfalse
otherwise.
Example Solution:
// 1. Function Declaration
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Sam"); // Outputs: Hello, Sam!
// 2. Function Expression
const subtract = function(a, b) {
return a - b;
};
console.log(subtract(10, 4)); // Outputs: 6
// 3. IIFE
(function() {
console.log("Executed immediately!");
})();
// 4. Function to Check if Number is Even
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Outputs: true
console.log(isEven(7)); // Outputs: false
12. Best Practices for Using Functions
- Use Descriptive Names: Name your functions based on the action they perform (e.g.,
calculateTotal
). - Keep Functions Focused: Each function should perform a single, well-defined task.
- Limit Parameters: Aim to keep functions small and avoid excessive parameters for readability.
- Return Early: If possible, use the
return
statement early in a function to simplify logic and reduce nesting.
Conclusion
In this lesson, you learned about function declarations and expressions, how to pass parameters and return values, and the difference between anonymous and named functions. Functions are essential for creating modular, organized, and reusable code, setting the foundation for more advanced programming concepts in JavaScript.
In the next lesson, we will cover Arrow Functions, where you’ll learn a more concise syntax for writing functions in JavaScript.