Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Parâmetros e Valores de Retorno | Section
Fundamentos de JavaScript

bookParâmetros e Valores de Retorno

Deslize para mostrar o menu

When you call a function like calculateRectangleArea, you provide values known as arguments. These arguments are passed to the function's parameters, in this case, width and height.

123456
function calculateRectangleArea(width, height) { return width * height; } const area = calculateRectangleArea(5, 3); console.log("The area of the rectangle is:", area);
copy

Inside the function, you can use these parameters as variables. When the function completes its calculation, it uses the return keyword to send a value back to where it was called. Here, width * height is returned, so when you call calculateRectangleArea(5, 3), the function returns 15, which is then stored in the area variable. The console.log statement prints this result for you to see.

Note
Note

A function can only return one value at a time, and as soon as it reaches a return statement, it stops running and exits immediately. If you do not use return, the function returns undefined by default.

Functions can also have default parameters, which are values that are used if no argument is provided for a parameter. This makes your functions more flexible and prevents errors if a value is missing. You can also use return early in a function if a certain condition is met and you want to exit before reaching the end.

For example, you could write a function like this:

12345678910
function greet(name = "Guest") { if (!name) { return "No name provided."; } return "Hello, " + name + "!"; } console.log(greet()); console.log(greet("")); console.log(greet("Alice"));
copy

If you call greet() with no argument, it uses the default "Guest". If you call greet(""), the function returns early with "No name provided.". This approach helps you handle different scenarios and makes your code easier to maintain.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 10

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 10
some-alt