JavaScript Functions Basics
Functions are reusable blocks of code that perform specific tasks. They are the building blocks of JavaScript programs.
Function Declarations
function add(a, b) {
return a + b;
}
let result = add(5, 3); // 8
Declarations are hoisted — they can be called before they appear in the code.
Function Expressions
Functions can be assigned to variables:
let multiply = function(a, b) {
return a * b;
};
let result = multiply(4, 5); // 20
Default Parameters
Provide default values if no argument is passed:
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet("John"); // "Hello, John!"
greet("John", "Hi"); // "Hi, John!"
Return Values
function getFullName(first, last) {
return `${first} ${last}`;
}
let name = getFullName("John", "Doe"); // "John Doe"
Remember: A function without return returns undefined.
Arrow Functions
Shorter syntax for function expressions:
// Traditional
let add = function(a, b) { return a + b; };
// Arrow
let add = (a, b) => a + b;
Single expression functions get an implicit return.
Complete Example: Calculator
function calculate(num1, num2, operator) {
switch (operator) {
case "add": return num1 + num2;
case "subtract": return num1 - num2;
case "multiply": return num1 * num2;
case "divide": return num1 / num2;
default: return NaN;
}
}
calculate(10, 5, "add"); // 15
calculate(10, 5, "multiply"); // 50
Complete Example: Data Processor
function processData(data, transform) {
return data.map(transform);
}
let numbers = [1, 2, 3, 4, 5];
let doubled = processData(numbers, (n) => n * 2);
// [2, 4, 6, 8, 10]
let names = ["alice", "bob", "charlie"];
let capitalized = processData(names, (n) => n.charAt(0).toUpperCase() + n.slice(1));
// ["Alice", "Bob", "Charlie"]
Best Practices
- Keep functions small — One responsibility per function
- Use descriptive names —
calculateTotal()notcalc() - Use default parameters — For optional values
- Return early — Reduce nesting with early returns
- Avoid side effects — Pure functions are easier to test
Common Mistakes
- Forgetting
return— Functions returnundefinedby default - Using
varin functions — Useletorconst - Confusing parameters and arguments — Parameters in definition, arguments in call
- Using arrow functions for methods — They don’t have their own
this - Deep nesting — Break complex logic into smaller functions