Functions are reusable blocks of code designed to perform a specific task. JavaScript supports Function Declarations (hoisted), Function Expressions, Arrow Functions, and ES6 default/rest parameters.
flowchart TD
Functions["JavaScript Functions"] --> Decl["Function Declaration: function foo() {} (Hoisted)"]
Functions --> Expr["Function Expression: const foo = function() {}"]
Functions --> Arrow["Arrow Function: const foo = () => {}"]
| Function Style | Hoisted? | Has Own this? |
Has arguments Object? |
Can Be Used as Constructor (new)? |
|---|---|---|---|---|
| Declaration | Yes | Yes | Yes | Yes |
| Expression | No (Follows const/let TDZ) |
Yes | Yes | Yes |
| Arrow Function | No | No (Lexical this) |
No (Use Rest ...args) |
No |
// Demonstrating function declarations, expressions, default parameters, and rest parameters
// 1. Function Declaration (Hoisted)
console.log(`Calculated Area: ${calculateArea(10, 5)}`); // Invoked before declaration!
function calculateArea(width, height = 1) { // Default parameter height = 1
return width * height;
}
// 2. Function Expression
const formatCurrency = function(amount, currencySymbol = "$") {
return `${currencySymbol}${amount.toFixed(2)}`;
};
console.log(formatCurrency(49.9));
// 3. Rest Parameters (...numbers)
function sumAllNumbers(...numbers) {
return numbers.reduce((accumulator, current) => accumulator + current, 0);
}
console.log(`Sum of Rest Parameters: ${sumAllNumbers(10, 20, 30, 40)}`); // 100
// 4. First-Class Functions (Passing functions as arguments)
function processUserAction(userId, callback) {
console.log(`Processing action for User #${userId}...`);
const status = "SUCCESS";
callback(status);
}
processUserAction(402, (result) => {
console.log(`Callback Executed! Result: ${result}`);
});
param = defaultValue) instead of relying on manual param = param || fallback checks inside function bodies.this binding inside array methods (map, filter).return statement return undefined by default.Write a function multiply(factor, ...numbers) that multiplies each number in numbers by factor and returns the resulting array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.