A function is a reusable block of code that performs a specific task. Instead of writing the same logic over and over, you define it once as a function and then call it wherever you need that behavior. Functions are one of the most fundamental building blocks in JavaScript — almost everything you write, from a button click handler to an API request, happens inside a function.
JavaScript gives you two main ways to define a function: function declarations and function expressions. Both create a function, but they behave differently in a few important ways.
Function Declarations
A function declaration starts with the function keyword, followed by a name, a list of parameters in parentheses, and a body in curly braces.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Asha"));
Output:
Hello, Asha!
Here, name is a parameter — a placeholder variable listed in the function definition. When you call greet("Asha"), "Asha" is the argument — the actual value passed in. The return statement sends a value back to wherever the function was called; if a function has no return, it implicitly returns undefined.
Function declarations are hoisted, meaning you can call one before it appears in your file, and JavaScript will still find it — the full mechanics of this are covered in the scope and hoisting tutorial.
Function Expressions
A function expression assigns an unnamed (or named) function to a variable instead. Unlike declarations, function expressions are not hoisted — the variable exists, but it isn't assigned the function until that line actually runs.
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(4, 5));
Output:
20
A more modern, shorter way to write a function expression is with an arrow function, which this course covers separately since it has a few behavioral differences worth understanding on their own.
Parameters, Default Values, and Multiple Returns
A function can take any number of parameters, and JavaScript won't complain if you call it with too few or too many arguments — missing parameters simply become undefined inside the function.
function area(width, height) {
if (width <= 0 || height <= 0) {
return 0;
}
return width * height;
}
console.log(area(5, 3));
console.log(area(5));
Output:
15
NaN
Notice area(5) returns NaN — height was undefined, and 5 <= 0 || undefined <= 0 evaluates to false, so the function falls through to width * height, which is 5 * undefined. This is exactly the kind of bug that default parameters are designed to prevent — you'll see that pattern next.
Once you're comfortable defining functions, the natural next step is learning how they interact with arrays — many of the most useful built-in array methods, like map() and filter(), work by taking a function as an argument.
