By the end of this lesson, you will understand how to Return Results and Use Default Parameters in JavaScript.
Return results and default parameters make functions flexible and effective. When you create a function, you can specify what it sends back. This enhances its functionality. It’s like ordering food; for instance, if you don’t specify a dish, you might receive a default option from the menu. For example, you might go to a restaurant and order coffee, but if you don’t mention the size, you may receive a medium cup by default. Therefore, understanding these concepts will help you work more efficiently when coding.
When you use the return statement in a function, you allow that function to output a value. This output can be used later in your program. In our earlier coffee ordering scenario, the returned message informs the user about their order. This means you are creating interactive and dynamic applications. Thus, knowing how to return results is crucial in JavaScript programming.
File: coffeeOrder.js
function orderCoffee(size = 'medium') {
return 'You ordered a ' + size + ' coffee.';
}
console.log(orderCoffee()); // No size provided
console.log(orderCoffee('large')); // Size provided
You ordered a medium coffee.
You ordered a large coffee.
In the function orderCoffee, the parameter size is critical. If no size is provided, it defaults to 'medium'. The return statement sends back a message about the coffee ordered. As a result, users see feedback based on their input. Additionally, the two console.log calls show how the function behaves when an argument is passed or when it is omitted.
Now, let’s build on our understanding. Create a function named calculateArea that calculates the area of a rectangle. Use two parameters, length and width, and set a default value for width if it’s not specified. By practicing this, you will further solidify your grasp on how to Return Results and Use Default Parameters.
function calculateArea(length, width = 5) {
return length * width;
}
console.log(calculateArea(10)); // Width defaults to 5
console.log(calculateArea(10, 3)); // Width is 3
return keyword to get a value back from a function.