Function Parameters
Functions in JavaScript can accept one or more parameters, which are placeholders for values that will be passed into the function when it is called. Parameters allow us to make our functions more flexible and reusable by allowing different values to be used each time the function is called.
To define parameters for a function, we list them within the parentheses after the function name. We can then use these parameters as variables within the function's block of code.
Here's an example of a function that takes in two parameters num1
and num2
, adds them together, and returns the result:
1function add(num1, num2) {
2 return num1 + num2;
3}
4
5// Call the add function
6// Output: 5
7console.log(add(2, 3));
Math.random()
is a built-in JavaScript function that generates a random number between 0 and 1. We can use this function to simulate a coin flip by checking if the generated number is less than 0.5.
xxxxxxxxxx
function coinFlip() {
if (Math.random() < 0.5) {
console.log('Heads');
} else {
console.log('Tails');
}
}
coinFlip();