Functions are a fundamental concept in JavaScript. They allow you to encapsulate a block of code, give it a name, and reuse it throughout your program. Here’s a breakdown of how functions work in JavaScript:
Function Declaration
You can declare a function using the function keyword followed by the function name, parameters (if any), and the function body enclosed in curly braces {}.
function greet(name) {
console.log("Hello, " + name + "!");
}
Function Expression
You can also define a function using a function expression, where the function is assigned to a variable.
const greet = function(name) {
console.log("Hello, " + name + "!");
};
Arrow Function
Arrow functions provide a more concise syntax for writing functions, especially for simple functions.
const greet = (name) => {
console.log("Hello, " + name + "!");
};
Invoking Functions
To execute a function, you simply use its name followed by parentheses ().
greet("John"); // Output: Hello, John!
Return Statement
Functions can return values using the return statement. Once a return statement is encountered, the function exits immediately, and the value is returned.
function add(a, b) {
return a + b;
}
const result = add(3, 5);
console.log(result); // Output: 8
Function Parameters
Functions can accept parameters, which are placeholders for values that the function will use when it’s called.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
Default Parameters
You can also provide default values for parameters.
function greet(name = "World") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, World!
greet("Bob"); // Output: Hello, Bob!
Function Scope
Variables declared inside a function are scoped to that function and are not accessible outside of it.
function myFunction() {
const message = "Hello";
console.log(message);
}
myFunction(); // Output: Hello
console.log(message); // Error: message is not defined
Functions are versatile and powerful tools in JavaScript, allowing you to organize and reuse code effectively.