By the end of this lesson, you will understand how to pass information with parameters and arguments in functions. This skill is crucial for creating dynamic, reusable code in JavaScript.
Functions can take inputs, which we call parameters. When you call a function, you provide specific values for these parameters. These values are known as arguments. For example, if you have a function designed to greet someone, you can pass the person’s name as an argument.
To further understand how to function arguments, let’s look at a simple function. In JavaScript, a function can take multiple parameters. Each of these can accept different kinds of data. Therefore, you can create versatile functions that work well with various inputs.
Imagine you want to personalize a greeting. Instead of always saying “Hello!”, you want it to say “Hello, Alice!” or “Hello, Bob!” You can achieve this by passing the names as arguments to your greeting function. This makes your greeting more personal and engaging.
File: greet.js
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Call with argument 'Alice'
greet('Bob'); // Call with argument 'Bob'
Hello, Alice!
Hello, Bob!
In the function greet, name is the parameter. When we call greet('Alice'), 'Alice' is the argument that gets passed to the function. The function then displays a personalized greeting using that name. This is a clear example of how to using parameters in functions efficiently.
Now it’s your turn! Write a function called farewell that takes a person’s name as a parameter and logs a goodbye message to the console. For example, it should log “Goodbye, Alice!” when called with the argument ‘Alice’. This task will help reinforce your understanding of how parameters and arguments work together.
function farewell(name) {
console.log(`Goodbye, ${name}!`);
}
farewell('Alice'); // Call with argument 'Alice'
For more practice, check out the lesson on setting up your development environment before diving deeper into more complex projects.