Defining Functions in JavaScript
Functions are reusable blocks of code that perform a specific task. In JavaScript, functions can be defined in multiple ways.
🧱 1. Function Declaration
This is the most common way to define a function.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
💡 2. Function Expression
Functions can also be assigned to variables.
const greet = function(name) {
return "Hi, " + name + "!";
};
console.log(greet("Bob"));
⚡ 3. Arrow Functions (ES6+)
Shorter syntax for writing functions, especially useful in callbacks.
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
📘 Parameters & Return
Functions can take parameters and return a value using the return
keyword.
function square(x) {
return x * x;
}
let result = square(4);
console.log(result); // 16
📝 Note: Function declarations are hoisted. This means they can be called before they are defined in the code.