No announcement
 

Parameters, Arguments and Return Statement

Parameters and Arguments

Parameters are variables defined in the function declaration that act as placeholders for values passed to the function when it is called. Arguments, on the other hand, are the actual values passed to the function during the function call.

Example:

parameter_arguments.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Parameters and Arguments Example</title>
</head>
<body>

<h2>JavaScript Parameters and Arguments:</h2>
<script>
function greet(name) {
  console.log("Hello, " + name + "!");
}

let personName = "John";
greet(personName); // Passing "John" as an argument to the greet function
</script>

</body>
</html>

Output
Hello, John!

In this example, we have a function greet that takes a single parameter name. When we call the function greet(personName), we pass the value of the personName variable (which is "John") as an argument to the function. Inside the function, the name parameter holds the value "John", and the function displays "Hello, John!" as output.

Return Statement

The return statement is used to specify the value that a function should return after it is called. When a function encounters a return statement, it immediately exits the function and sends the specified value back to the calling code.

Example:

return.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Return Statement Example</title>
</head>
<body>

<h2>JavaScript Return Statement:</h2>
<script>
function addNumbers(a, b) {
  let sum = a + b;
  return sum;
}

let result = addNumbers(5, 10);
console.log("Sum:", result); // Output: Sum: 15
</script>

</body>
</html>

Output
Sum: 15

In this example, we defined a function addNumbers that takes two parameters a and b. Inside the function, we calculate the sum of a and b and store it in the sum variable. We then use the return statement to send the value of sum (which is 15) back to the calling code. The value returned by the function is assigned to the result variable, and the output displays "Sum: 15".

Using parameters, arguments, and the return statement allows us to create functions that can take inputs, process them, and provide meaningful outputs, making our code more versatile and modular.