JavaScript Functions
Reusable blocks of code that perform specific tasks
🔧 What are Functions?
Functions are reusable blocks of code that perform specific tasks. Think of them as mini-programs that you can call whenever you need them.
// Creating a simple function
function sayHello() {
console.log("Hello, World!");
}
// Calling the function
sayHello(); // Output: Hello, World!
Function Features
Reusable
Write once, use many times
function greet() {
console.log("Hi!");
}
greet(); // Use it
greet(); // Use again
Parameters
Accept input values
function greet(name) {
console.log("Hi " + name);
}
greet("Alice");
Return Values
Send results back
function add(a, b) {
return a + b;
}
let result = add(5, 3);
Local Scope
Variables stay inside functions
function test() {
let x = 10; // Only inside
}
// x not available here
🔹 Basic Function Syntax
Here's how to create and use functions:
// Function declaration
function functionName() {
// Code to execute
console.log("This is a function!");
}
// Call the function
functionName();
// Function with parameters
function greetUser(userName) {
console.log("Welcome, " + userName + "!");
}
// Call with arguments
greetUser("Sarah");
greetUser("Mike");
Console Output:
This is a function!
Welcome, Sarah!
Welcome, Mike!
Welcome, Sarah!
Welcome, Mike!
🔹 Functions with Return Values
Functions can calculate and return results:
// Function that returns a value
function calculateArea(width, height) {
let area = width * height;
return area;
}
// Use the returned value
let roomArea = calculateArea(10, 12);
console.log("Room area:", roomArea + " square feet");
// Function that returns a greeting
function createGreeting(name, time) {
return "Good " + time + ", " + name + "!";
}
let morning = createGreeting("Emma", "morning");
let evening = createGreeting("John", "evening");
console.log(morning);
console.log(evening);
Console Output:
Room area: 120 square feet
Good morning, Emma!
Good evening, John!
Good morning, Emma!
Good evening, John!
🔹 Function Expressions
Another way to create functions:
// Function expression
const multiply = function(a, b) {
return a * b;
};
// Arrow function (modern way)
const divide = (a, b) => {
return a / b;
};
// Short arrow function
const square = x => x * x;
// Using the functions
console.log("Multiply:", multiply(4, 5));
console.log("Divide:", divide(20, 4));
console.log("Square:", square(6));
Console Output:
Multiply: 20
Divide: 5
Square: 36
Divide: 5
Square: 36
🔹 Default Parameters
Set default values for parameters:
// Function with default parameters
function orderCoffee(size = "medium", type = "regular") {
return "One " + size + " " + type + " coffee, please!";
}
// Call with different arguments
console.log(orderCoffee()); // Uses defaults
console.log(orderCoffee("large")); // Uses default type
console.log(orderCoffee("small", "decaf")); // Uses both arguments
// Function with default calculation
function calculateTip(bill, tipPercent = 15) {
return bill * (tipPercent / 100);
}
console.log("Tip for $50:", "$" + calculateTip(50));
console.log("Tip for $30 at 20%:", "$" + calculateTip(30, 20));
Console Output:
One medium regular coffee, please!
One large regular coffee, please!
One small decaf coffee, please!
Tip for $50: $7.5
Tip for $30 at 20%: $6
One large regular coffee, please!
One small decaf coffee, please!
Tip for $50: $7.5
Tip for $30 at 20%: $6
🔹 Practical Function Examples
Real-world function examples:
// Check if a number is even
function isEven(number) {
return number % 2 === 0;
}
// Convert temperature
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Validate email (simple check)
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
// Generate random number
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Test the functions
console.log("Is 8 even?", isEven(8));
console.log("25°C in Fahrenheit:", celsiusToFahrenheit(25));
console.log("Is '[email protected]' valid?", isValidEmail("[email protected]"));
console.log("Random number 1-10:", randomBetween(1, 10));