Functions are reusable blocks of code designed to perform a specific task. They help organize code, avoid repetition, and improve readability.
Basic Syntax
A function is defined using the function keyword, followed by a name, parentheses for parameters, and a block of code:
📌 Deep Dive: Defining and Calling a Function
function greet() {
console.log("Hello, world!");
}
greet();
Function Parameters and Arguments
Functions can accept inputs called parameters. When you call the function, you provide arguments to fill those parameters.
📌 Deep Dive: Parameters and Arguments
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
greet("Bob");
Hello, Bob!
Return Values
Functions can return a value using the return statement. This allows the function to output a result that can be stored or used elsewhere.
📌 Deep Dive: Returning a Value
function add(a, b) {
return a + b;
}
const sum = add(5, 3);
console.log(sum);
Function Expressions
Functions can also be stored in variables. These are called function expressions.
📌 Deep Dive: Function Expression
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 6));
Arrow Functions (ES6+)
A concise syntax for function expressions, especially useful for simple functions.
📌 Deep Dive: Arrow Function Syntax
const square = n => n * n;
console.log(square(5));

💡 Important:
Functions without a return statement return undefined by default.
| Type | Description |
|---|---|
| Function Declaration | Hoisted, named function usable before declaration. |
| Function Expression | Stored in variables, not hoisted. |
| Arrow Function | Short syntax, no own this, good for callbacks. |
⚠️ Note on Hoisting
Function declarations are hoisted, so you can call them before their definition. Function expressions and arrow functions are not hoisted.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does a function return if there is no return statement?
Question 2 of 2
Which function type is hoisted and can be called before its declaration?
Loading results...