Function Parameters and Return
Introduction
In JavaScript, a function is a block of code designed to perform a particular task. A function is executed when something invokes it, or calls it. A function in JavaScript can take parameters and may return a value. In this lesson, we'll introduce you to the concept of function parameters and return values in JavaScript.
Function Parameters
When defining a function, you can specify its parameters. Parameters are values that the function takes in when it is invoked. They are placed in the parentheses (()
) after the function name, and are separated by commas if more than one. Here is an example of a function with parameters:
function greet(name, age) {
console.log("Hello " + name + ", you are " + age + " years old.");
}
In this function, name
and age
are parameters. When you call this function, you pass the arguments in the same order.
greet("John", 30); // Outputs: Hello John, you are 30 years old.
In the example above, "John" and 30 are the arguments that are passed to the function.
Understanding “undefined”
In JavaScript, if a function is called with missing arguments (less than declared), the missing values are set to: undefined
.
greet("John"); // Outputs: Hello John, you are undefined years old.
Function Return
A function can optionally return a value as a result. When JavaScript reaches a return
statement, the function will stop executing, and return the specified value. If no return statement is provided, or the return statement doesn’t include any expression, the function returns undefined
.
Let's take a look at an example:
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Outputs: 8
In this function, a
and b
are parameters. The function adds the two parameters together, and then returns
the result.
The return Keyword
The return
keyword is powerful because it allows functions to produce an output. We can then take this output and store it in a variable for future use.
function square(number) {
return number * number;
}
let result = square(5);
console.log(result); // Outputs: 25
In the example above, the square
function returns the square of the input number. We store the output in the result
variable and then log it to the console.
Conclusion
In JavaScript, functions often take parameters and return a value. Parameters allow us to pass values to our functions, which our functions can then manipulate to produce a result. By using the return
keyword, our functions can output a value that we can store in a variable for later use. Understanding these concepts is key to mastering JavaScript, as they form the basis of many coding tasks.