JavaScript Functions
When we last left off in my previous post, Bootcamp 50 Days In Review, I mentioned that I was to the point in my bootcamp where we were starting to learn about JavaScript. We had a few lessons that went over some of the basics we needed to know, but the meat of the lessons came when we got to the section about functions. In our "Introducing Functions" section we covered arguments, multiple arguments, and the return value.
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
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.
Multiple Arguments
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!".
Return
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.
So that's it for our Introduction to JavaScript Functions! In the next article I'll talk about leveling up our functions using things like scope, function expressions, and defining methods.
- Avery Ramirez
Top comments (0)