A function in JavaScript is a block of reusable code that performs a specific task. It helps in writing cleaner, modular, and efficient code by avoiding repetition.
A function is defined using the function keyword followed by a name, parentheses (), and a block of code {}.
function greet() {
console.log("Hello, welcome to JavaScript!");
}
To execute a function, simply call it by its name followed by ().
greet(); // Output: Hello, welcome to JavaScript!
Functions can accept parameters (input values) and use them inside the function.
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice"); // Output: Hello, Alice!
💡 Parameters are placeholders, while arguments are actual values passed when calling the function.
A function can return a value using the return statement.