Function Basics
Functions are reusable blocks of code that perform a specific task. They are fundamental to JavaScript programming.
Function Declaration:
function name(parameters) { return value; }
- Hoisted (can be called before declaration)
- Named, making debugging easier
Function Expression:
const name = function(parameters) { return value; }
- Not hoisted (must be defined before use)
- Can be anonymous
Arrow Functions (ES6+):
const name = (parameters) => { return value; }
- Shorter syntax
- No own
thisbinding - Cannot be used as constructors
Parameters vs Arguments:
- Parameters: Variables in the function definition
- Arguments: Values passed when calling the function
Return Values:
- Functions return undefined by default
- Use return to send back a value
- return exits the function immediately
Code Examples
Function Typesjavascript
// Function declaration (hoisted)
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
// Function expression (not hoisted)
const add = function(a, b) {
return a + b;
};
console.log("2 + 3 =", add(2, 3));
// Arrow function
const multiply = (a, b) => {
return a * b;
};
console.log("4 * 5 =", multiply(4, 5));
// Arrow function - concise body (implicit return)
const double = x => x * 2;
console.log("Double 6 =", double(6));
// Arrow function - no parameters
const getRandomNumber = () => Math.random();
console.log("Random:", getRandomNumber());
// Multiple statements need curly braces
const calculate = (a, b) => {
const sum = a + b;
const product = a * b;
return { sum, product };
};
console.log(calculate(3, 4));Arrow functions are preferred for short, simple functions. Use regular functions when you need 'this' binding or hoisting.
Parameters and Argumentsjavascript
// Default parameters
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // Uses both defaults
console.log(greet("Alice")); // Uses greeting default
console.log(greet("Bob", "Hi")); // No defaults used
// Rest parameters (...args)
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log("Sum:", sum(1, 2, 3, 4, 5));
// Spread operator in function calls
const nums = [10, 20, 30];
console.log("Max:", Math.max(...nums));
// Destructuring parameters
function printUser({ name, age, city = "Unknown" }) {
console.log(`${name}, ${age}, from ${city}`);
}
printUser({ name: "Alice", age: 30 });
// Early return pattern
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
console.log("10 / 2 =", divide(10, 2));
console.log("10 / 0 =", divide(10, 0));Default parameters and rest parameters make functions more flexible. Use early returns to handle edge cases cleanly.
Quick Quiz
1. What is hoisting in JavaScript?
2. What does a function return if there's no return statement?
Was this lesson helpful?