Our introduction to functions described them as "procedures that allow us to write reusable, modular code". We use them to define a chunk of code that we can then execute at a later point. The process to be put at it's simplest terms is to define a function and then run it, demonstrated plainly below:
Define a function called "printGreeting" that prints out the string "Hello!" Execute your function once.
Arguments are accessible objects inside functions that pass the values through to the function. If a function is called with missing values, it's set to undefined. Below is an exercise demonstrating a single string argument, but also introduced us to template literals which allow embedded expressions.
Define a function called "yell" which accepts a string argument called "message". This function should print out an uppercased version of message 3 times.
If you need to create a function with multiple arguments, you can define more than one parameter by separating them with a comma. Keep in mind, the order you put them in matters. Once you have all of your arguments defined, you have the option to return your content. The return statement ends function execution and specifies the value that is to be returned to the function caller.
Below is an exercise where we ran a function with multiple arguments to determine if the dice roll came out as snake eyes or not. It accepted two inputs, representing the two dice. If both of the numbers are 1, print "Snake Eyes!", otherwise print "Not Snake Eyes!".
The return keyword does just that - returns values when we call them. We can store these values inside of a function as well. Previously we used console.log to call these values, however it doesn't allow us to return the value and store it in a variable.
To demonstrate this, we did a simple function called "multiply", that accepts two numerical arguments and returns their product, by multiplying them together. Instead of just printing it with console.log, we're going to return the value.
When run, this returns the sum of your x and y arguments.
- Avery Ramirez