Functions
In this lesson, we'll get to know JavaScript functions. Let's begin!
As you learned in the previous chapter, functions are very important concepts in JavaScript.
In this section, you’ll dive deeper into the implementation of functions and get acquainted with many exciting features that make JavaScript functions powerful.
Function return values
Functions may retrieve results.
- You can use the
return
statement to pass back a result. - If you specify
return
with no value, the function will immediately return without a value. - If you utilize the result of a function that does not return a value, be prepared that you could get
undefined
.
The Listing below demonstrates this behavior:
Listing: Using return
in various ways in a function
<!DOCTYPE html> <html> <head> <title>Function return values</title> <script> function hasReturnValue() { return "Hey!"; } function noReturnValue1() { } function noReturnValue2() { return; } console.log(hasReturnValue()); // "Hey!" console.log(noReturnValue1()); // undefined console.log(noReturnValue2()); // undefined </script> </head> <body> Listing 8-3: View the console output </body> </html>
Function arguments
Functions may have arguments. In many languages, functions are identified by their signature that covers the name of the function and the type of their arguments in the order of their occurrence. In JavaScript, a function is identified only by its name. It does not matter how many arguments you defined when declaring the function or how many parameters you pass when invoking the very same function.
If you pass more arguments than defined, the extra ones will be passed to the function, but the function will ignore them unless it is prepared to handle them, as you’ll see soon. If you pass fewer arguments, the missing ones will have a value of undefined within the function body. So, this code is totally legal in JavaScript: