Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Parametere og returverdier | Seksjon
Javascript-Grunnleggende

bookParametere og returverdier

Sveip for å vise menyen

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 10

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 10
some-alt