Functions
Functions are reusable blocks of code that perform a specific task. They allow you to break down your code into smaller, more manageable pieces, making it easier to read, debug, and maintain. In JavaScript, you can create functions using the function
keyword.
Here's an example of a simple function that takes a name
parameter and logs a greeting message to the console:
1function greet(name) {
2 console.log(`Hello, ${name}!`);
3}
In this example, the greet
function takes a name
parameter. Inside the function body, it uses string interpolation to log a greeting message to the console, including the value of the name
parameter.
To call a function, you simply write the function name followed by parentheses. You can also pass arguments to the function inside the parentheses. For example, to call the greet
function with the name 'John'
, you would write:
1greet('John');
This will log the message Hello, John!
to the console.
Functions can also return values using the return
keyword. When a function encounters a return
statement, it stops executing and returns the specified value back to the caller. Here's an example:
1function add(a, b) {
2 return a + b;
3}
4
5const result = add(2, 3);
6console.log(result); // Output: 5
In this example, the add
function takes two parameters a
and b
. It adds the values of a
and b
together and returns the result using the return
statement. The returned value is then assigned to the result
variable and logged to the console, resulting in the output 5
.
Functions are an essential part of JavaScript and are used extensively in web development. They allow you to write reusable code and improve the modularity and maintainability of your applications.
xxxxxxxxxx
// Declare a function called `greet` that takes a `name` parameter
// and logs a greeting message to the console
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Call the `greet` function with the name `John`
greet('John');