In this chapter, we will learn about JavaScript functions. Functions are fundamental building blocks in JavaScript, allowing you to encapsulate reusable code blocks. We will cover:
- What is a Function?
- Defining a Function
- Calling a Function
- Function Parameters and Arguments
- Return Statement
- Function Expressions
- Arrow Functions
- Higher-Order Functions
- Simple Programs using Functions
What is a Function?
A function is a block of code designed to perform a particular task. It is executed when "called" or "invoked". Functions help you organize your code, make it reusable, and improve readability.
Defining a Function
You can define a function using the function
keyword followed by a name, parentheses ()
, and a block of code {}
.
Syntax
function functionName(parameters) { // code to be executed }
Example
function greet() { console.log("Hello, World!"); }
In the example above, a function named greet
is defined that prints "Hello, World!" to the console.
Calling a Function
You call a function by using its name followed by parentheses ()
.
Example
greet(); // Output: Hello, World!
In the example above, the greet
function is called, and it prints "Hello, World!" to the console.
Function Parameters and Arguments
Functions can take parameters (also called arguments) to perform operations using the input values.
Syntax
function functionName(parameter1, parameter2) { // code to be executed }
Example
function add(a, b) { console.log(a + b); } add(5, 3); // Output: 8
In the example above, the add
function takes two parameters, a
and b
, and prints their sum. The function is called with arguments 5
and 3
.
Return Statement
The return
statement is used to return a value from a function. When a return
statement is executed, the function stops executing.
Syntax
function functionName(parameters) { // code to be executed return value; }
Example
function multiply(a, b) { return a * b; } let result = multiply(4, 5); console.log(result); // Output: 20
In the example above, the multiply
function returns the product of a
and b
. The result is stored in the result
variable and printed to the console.
Function Expressions
A function expression defines a function as part of a larger expression syntax. Function expressions can be anonymous (without a name).
Example
let greet = function() { console.log("Hello, World!"); }; greet(); // Output: Hello, World!
In the example above, an anonymous function is assigned to the variable greet
, which can then be called like a regular function.
Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They are always anonymous and are best suited for non-method functions.
Syntax
let functionName = (parameters) => { // code to be executed };
Example
let add = (a, b) => { return a + b; }; console.log(add(2, 3)); // Output: 5
For simple expressions, you can omit the curly braces and the return
keyword.
Example
let multiply = (a, b) => a * b; console.log(multiply(3, 4)); // Output: 12
Higher-Order Functions
A higher-order function is a function that can take another function as an argument or return a function as a result. They are commonly used in functional programming.
Example
function applyOperation(a, b, operation) { return operation(a, b); } let sum = applyOperation(5, 10, (x, y) => x + y); console.log(sum); // Output: 15 let product = applyOperation(5, 10, (x, y) => x * y); console.log(product); // Output: 50
In the example above, the applyOperation
function takes two numbers and a function (operation
) as arguments. It applies the operation to the numbers and returns the result.
Simple Programs using Functions
Program 1: Calculate the Area of a Rectangle
function calculateArea(length, width) { return length * width; } let area = calculateArea(5, 10); console.log("Area of the rectangle:", area); // Output: Area of the rectangle: 50
Program 2: Check if a Number is Even or Odd
function isEven(number) { return number % 2 === 0; } let number = 7; if (isEven(number)) { console.log(number + " is even."); } else { console.log(number + " is odd."); } // Output: 7 is odd.
Program 3: Find the Maximum of Three Numbers
function findMax(a, b, c) { return Math.max(a, b, c); } let max = findMax(10, 20, 15); console.log("The maximum number is:", max); // Output: The maximum number is: 20
Program 4: Convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) { return (celsius * 9/5) + 32; } let fahrenheit = celsiusToFahrenheit(25); console.log("25°C is", fahrenheit, "°F"); // Output: 25°C is 77°F
Program 5: Generate a Random Number between a Range
function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } let randomNum = getRandomNumber(1, 100); console.log("Random number between 1 and 100:", randomNum);
Conclusion
In this chapter, you learned about JavaScript functions, including how to define, call, and use them with parameters and return values. We also explored function expressions, arrow functions, higher-order functions, and provided various use cases with simple programs to demonstrate the usage of functions. Understanding functions is crucial for writing modular and reusable code in JavaScript.