In JavaScript, a function is a block of code designed to perform a specific task.
You can define a function using the function keyword, and it can take parameters
and return a value. Here's a basic example:
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Calling the function
console.log(greet('Abebe')); // Output: Hello, Abebe!
Key Concepts
Function Declaration: The way to define a function using the function keyword.
Parameters: Values you can pass into the function. In the example, name is a
parameter.
Return Value: The value that the function sends back when called. You can use the
return statement for this.
Arrow Functions
You can also define functions using arrow syntax:
const greet = (name) => `Hello, ${name}!`;
console.log(greet('Amare')); // Output: Hello, Amare!
Function Expressions
Functions can also be defined as expressions and assigned to variables:
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
Summary
Functions are fundamental in JavaScript, allowing you to encapsulate code for reuse
and organization.