Functions
Writing reusable blocks of code with names, parameters, return values, declarations, and expressions.
A function is a named, reusable block of code. Instead of copying the same logic in multiple places, you write it once, give it a name, and call it whenever you need it.
You define a function with the function keyword, a name, and a pair of parentheses. The code inside the curly braces runs every time you call the function by its name.
function greet() {
console.log("Hello!");
}
greet(); // Hello!
greet(); // Hello!Parameters are the named inputs you declare in the parentheses. When you call the function, you pass arguments, the actual values, and the function receives them as those named variables.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Ana"); // Hello, Ana!
greet("World"); // Hello, World!A function can send a value back to the caller using return. Once return runs, the function stops immediately. Any code after it in the same function is skipped.
function add(a, b) {
return a + b;
}
const result = add(3, 4);
console.log(result); // 7There are two common ways to write a function. A function declaration uses the function keyword followed by a name. A function expression assigns an anonymous function to a variable.
The key difference is hoisting, which means declarations are available before the line where they appear. Function expressions are not hoisted, so they can only be called after the line that defines them.
// Declaration: works even though the call is above the definition.
greet("World"); // Hello, World
function greet(name) {
console.log("Hello, " + name);
}
// Expression: call it only after this line.
const farewell = function (name) {
console.log("Goodbye, " + name);
};
farewell("World"); // Goodbye, WorldIn production
Give functions names that describe their result or effect. A named function makes stack traces, logs, and code review much easier to follow.