Welcome to the JS Function Parameters tutorial! Today, we'll dive into one of the core aspects of JavaScript - function parameters. By the end of this lesson, you'll be able to create functions with multiple parameters, understand the importance of function arguments, and even tackle some real-world examples. Let's get started!
In simple terms, function parameters are values that we pass to a function when we call it. These values allow the function to perform different tasks based on the input provided.
function greet(name) {
console.log('Hello, ' + name);
}
greet('John'); // Output: Hello, JohnIn the example above, greet is a function with one parameter, name. When we call the greet function, we pass 'John' as an argument. The function then logs a personalized greeting.
function sum(num1, num2) {
let result = num1 + num2;
console.log('The sum is:', result);
}
sum(2, 3); // Output: The sum is: 5
sum('2', 3); // Output: The sum is: 23 (Concatenation of string '2' and number 3)
sum('2', '3'); // Output: The sum is: 23 (Concatenation of string '2' and string '3')In the above example, the sum function expects two numeric values. However, if we pass a string as an argument, JavaScript will concatenate the strings instead of adding them, resulting in unexpected output.
To avoid such situations, we can define default values for our function parameters. This way, if no argument is provided, the function will use the default value.
function sum(num1 = 0, num2 = 0) {
let result = num1 + num2;
console.log('The sum is:', result);
}
sum(2, 3); // Output: The sum is: 5
sum(2); // Output: The sum is: 2 (num2 defaults to 0)
sum(); // Output: The sum is: 0 (num1 and num2 default to 0)Function parameters play a crucial role in creating reusable and versatile functions, which is essential for building complex applications.
function calculateArea(width, height, shape) {
let area = 0;
switch (shape) {
case 'rectangle':
area = width * height;
break;
case 'circle':
area = Math.PI * Math.pow(width / 2, 2);
break;
default:
console.log('Invalid shape.');
}
console.log('The area is:', area);
}
calculateArea(5, 4, 'rectangle'); // Output: The area is: 20
calculateArea(3, Math.PI, 'circle'); // Output: The area is: 28.274333882308138What is the output of `sum('2', 3)`?
That's it for today! By learning about function parameters, you're taking another step towards becoming a JavaScript master. Stay tuned for more exciting topics! 🚀