Functions Basics
Functions in JavaScript
Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code that performs a specific task. You define it once and can call it multiple times throughout your program.
Why Use Functions?
- Reusability: Write code once, use it many times
- Organization: Break complex problems into smaller, manageable pieces
- Maintainability: Update code in one place rather than many
- Abstraction: Hide complex logic behind simple function names
Function Declaration
The most common way to create a function is with a function declaration:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob")); // Output: Hello, Bob!
Function Anatomy
function functionName(parameter1, parameter2) {
// Function body - code to execute
return result; // Optional return value
}
- function keyword: Declares a function
- functionName: Name you give the function
- parameters: Input values (optional)
- function body: Code that runs when called
- return: Sends a value back to the caller (optional)
Calling Functions
To use (or “call”) a function, write its name followed by parentheses:
function sayHello() {
console.log("Hello!");
}
sayHello(); // Call the function
// Output: Hello!
Parameters and Arguments
Functions can accept inputs called parameters:
function add(a, b) { // a and b are parameters
return a + b;
}
let sum = add(5, 3); // 5 and 3 are arguments
console.log(sum); // Output: 8
You can have multiple parameters or none at all:
function noParams() {
return "I take no parameters";
}
function threeParams(x, y, z) {
return x + y + z;
}
Return Values
The return statement sends a value back from the function:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result); // Output: 20
Without a return statement, a function returns undefined:
function noReturn() {
let x = 5 + 5;
// No return statement
}
console.log(noReturn()); // Output: undefined
Important: Code after a return statement won’t execute:
function example() {
return "Done";
console.log("This never runs");
}
Function Expressions
You can also assign functions to variables:
const greet = function(name) {
return "Hi, " + name;
};
console.log(greet("Charlie")); // Output: Hi, Charlie
The difference from function declarations:
- Function declarations are hoisted (can be called before they’re defined)
- Function expressions are not hoisted
// This works - hoisting
sayHi();
function sayHi() {
console.log("Hi!");
}
// This fails - not hoisted
sayBye(); // Error!
const sayBye = function() {
console.log("Bye!");
};
Default Parameters
You can provide default values for parameters:
function greet(name = "Guest") {
return "Hello, " + name;
}
console.log(greet()); // Output: Hello, Guest
console.log(greet("Emma")); // Output: Hello, Emma
Scope
Variables inside functions are local to that function:
function example() {
let localVar = "I'm local";
console.log(localVar); // Works
}
example();
console.log(localVar); // Error! localVar is not defined
Common Patterns
1. Helper Functions:
function calculateTotal(price, taxRate) {
return price + (price * taxRate);
}
function formatPrice(amount) {
return "$" + amount.toFixed(2);
}
let total = calculateTotal(100, 0.08);
console.log(formatPrice(total)); // Output: $108.00
2. Functions Calling Functions:
function square(n) {
return n * n;
}
function sumOfSquares(a, b) {
return square(a) + square(b);
}
console.log(sumOfSquares(3, 4)); // Output: 25
Best Practices
- Use descriptive names:
calculateTax()notcalc() - Keep functions small: Each function should do one thing well
- Avoid side effects: Functions should primarily work with parameters and return values
- Use consistent naming:
getUserData(),getProductData()notgetUserData(),fetchProduct()
Next Article: Arrow Functions