Example 1: Simple Calculator
A calculator that performs basic arithmetic operations using a function that takes a callback.
function calculate(a, b, operation) {
switch (operation) {
case "add": return a + b;
case "subtract": return a - b;
case "multiply": return a * b;
case "divide": return b !== 0 ? a / b : "Cannot divide by zero";
default: return "Unknown operation";
}
}
console.log(calculate(10, 5, "add"));
console.log(calculate(10, 5, "multiply"));
console.log(calculate(10, 0, "divide"));
Try it Yourself →
Example 2: Email Validator
Validate email addresses with a simple regex-based function.
function validateEmail(email) {
const pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return pattern.test(email);
}
function checkEmail(email) {
if (validateEmail(email)) {
return "Valid email address";
}
return "Invalid email address";
}
console.log(checkEmail("user@example.com"));
console.log(checkEmail("invalid-email"));
console.log(checkEmail("user@.com"));
Try it Yourself →
Example 3: Array Manipulation
Chain array methods to transform, filter, and sort data.
const products = [
{ name: "Laptop", price: 1200, inStock: true },
{ name: "Mouse", price: 25, inStock: true },
{ name: "Keyboard", price: 80, inStock: false },
{ name: "Monitor", price: 300, inStock: true }
];
const available = products
.filter(p => p.inStock)
.map(p => ({ name: p.name, price: "$" + p.price }))
.sort((a, b) => a.name.localeCompare(b.name));
console.log(available);
Try it Yourself →