Function Fundamentals: Mastering JavaScript's Reusable Code
Contents
Introduction
Defining Functions
Calling Functions
Passing Arguments
Best Practices
Projects
References & Resources
Imagine writing the same code repeatedly in your JavaScript program. Tedious, right? That's where functions come in! They're the reusable blocks of code that save you time and make your programs cleaner and more efficient. This concise guide will equip you with everything you need to know about defining, calling, and passing arguments to functions in JavaScript.
- Use the
function
keyword followed by a name and parentheses:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
- You can specify arguments enclosed in the parentheses.
- The function body contains the code to be executed.
- Use the function name followed by parentheses:
sayHello("John"); // Outputs: "Hello, John!"
- You can pass arguments inside the parentheses when calling the function.
- Arguments are like variables that receive values when the function is called:
function addNumbers(x, y) {
return x + y;
}
let result = addNumbers(5, 10); // result will be 15
- The number of arguments passed should match the function's definition.
- Choose meaningful function names that describe their purpose.
- Use comments to explain what the function does and its arguments.
- Avoid too many arguments; keep functions focused and modular.
- Consider returning values from functions for flexibility.
- Practice writing different types of functions to solidify your understanding.
Projects
Project 1: Rock, Paper, Scissors Game
function playRockPaperScissors() {
const userChoice = prompt("Choose rock, paper, or scissors:").toLowerCase();
const computerChoice = ["rock", "paper", "scissors"][Math.floor(Math.random() * 3)];
function determineWinner(user, computer) {
if (user === computer) {
return "It's a tie!";
} else if ((user === "rock" && computer === "scissors") ||
(user === "paper" && computer === "rock") ||
(user === "scissors" && computer === "paper")) {
return "You win!";
} else {
return "Computer wins!";
}
}
const result = determineWinner(userChoice, computerChoice);
console.log(`You chose ${userChoice}, computer chose ${computerChoice}. ${result}`);
}
playRockPaperScissors();
Project 2: Simple Calculator
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function divide(x, y) {
if (y === 0) {
return "Cannot divide by zero";
} else {
return x / y;
}
}
let operation = prompt("Choose an operation (+, -, *, /):");
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));
let result;
switch (operation) {
case "+":
result = add(num1, num2);
break;
case "-":
result = subtract(num1, num2);
break;
case "*":
result = multiply(num1, num2);
break;
case "/":
result = divide(num1, num2);
break;
default:
console.log("Invalid operation");
return;
}
console.log(`The result is: ${result}`);
Project 3: Password Validator
function validatePassword(password) {
const requirements = {
minLength: 8,
uppercase: /[A-Z]/,
lowercase: /[a-z]/,
number: /[0-9]/,
symbol: /[!@#$%^&*()_+-=[]{};':"\\|,.<>?]/
};
let isValid = true;
for (const [requirement, regex] of Object.entries(requirements)) {
if (!regex.test(password)) {
console.log(`Password must include ${requirement}`);
isValid = false;
}
}
if (isValid) {
console.log("Password is valid!");
}
}
const userPassword = prompt("Enter a password to validate:");
validatePassword(userPassword);
References:
Check out MDN Web Docs for comprehensive documentation on JavaScript functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Top comments (0)