Using Functions to Solve Complex JavaScript Problems – JavaScript 101

JavaScript 101 is a series of instructional videos given by DevMountain Web Development Instructors. Click here to see the entire video series

You can either write your own functions or use a pre-written set of functions in your programming language code library, to perform specialized tasks. Creating these functions is one thing, but you will need to master the idea that you can stack multiple programming steps in a single action when you program your functions correctly. In this video, you will learn how to use functions to solve complex JavaScript problems. 

Video Transcription

JavaScript provides functions similar to most of the scripting and programming languages. Functions are one of the fundamental building blocks in JavaScript. In JavaScript specifically, a function, allows you to define a block of code, give it a name and then execute it as many times as you want. 

Functions are a “subprogram” that can be called by code external (or internal in the case of recursion) to the function.  They are first-class objects because they have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.

When you create a function, it can contain any amount of code and any type of code. You can create variables, change variables, perform logical comparisons with conditionals and any number of other tasks all contained within a single function. Creating functions is one thing, but a whole other skill we need to master is the idea that we can stack multiple programming steps in a single action when we program our functions correctly.

For example, it may seem easy to create a function that adds numbers together because that’s just a single action. But functions can be so much more powerful when you think of them as something that contains any repeatable number of steps. Remember back to our discussion on computational thinking. Part of programming means creating algorithms that leverage repeatable steps. So don’t limit what you think functions can do by thinking they can only do one thing. A function can run a single line of code like adding two numbers together or hundreds of lines of code like searching thousands of entries in a database and finding a single item. Anything, no matter how long, can be contained within a function.

The Flexibility of Functions 

Additionally, the flexibility that functions provide our code means that we need to keep track of where data is being passed. For example, if I were to create a function for counting up on a certain variable, then my function wouldn’t need to pass any data at all. My function would just count up on that variable. But if I wanted to create a more flexible function that would add one to any number or to any variable, then I would need a way to tell that function which variable to manipulate. This way I can choose what variable needs to be changed by choosing what is passed into the function.

What are parameters? 

Functions use an input mechanism to determine what data will be passed to that function. These are called parameters. We’ve discussed them before, but they are the secret weapon to functions that make the difference between rigid functions and more powerful and flexible actions that your code can complete.

Using Parameters to Create a Flexible Function

Let’s look back at a messenger app to show what I mean about using parameters to create a flexible function. Let’s say that every time someone clicks send, you want to execute a function that will display the words they’ve typed on the screen. We can’t do that without passing data into the function. That’s because we don’t want the function to send a set response. We want it to send whatever the user types. And so we need to pass that data into the function some way. We do this using parameters. Callbacks are a pattern. They’re not syntax. When we send parameters into a function, we could send in another function instead of a number, string, or other simple data type. This allows the receiving function to invoke a function we passed in whenever it needs to.

We do this pattern in real life whenever we give a phone number to someone else. Let’s say I use Steve to help me do task A and Dave helps me do task B. Steve and Dave are both functions that I invoke by calling them on their phones. What if I gave Dave’s number to Steve? When is Steve going to call Dave? I don’t know. And it doesn’t matter. Steve now controls when to bring Dave in for help. 

A common application of this in our code is handling click events. We don’t know when the user is going to click the button. So we give the JavaScript engine a function it can use to help when the button is clicked. We don’t run the function. We create the instructions and pass them along. We’ll look at that more on our syntax videos coming up. 

Multi-Line Functions 

Let’s talk about multi-line functions or functions that do multiple things for us. Functions are one of the building blocks of JavaScript. And they can be so powerful. They can do so many different things for us. So I’m going to introduce multi-line functions or functions that are performing multiple tasks.

Multi-Line Functions – Practice I

Let’s take a look at the code editor. In the code editor, I’m gonna create a function called sentence maker. And inside the curly brackets for sentence maker, first thing I’m gonna do is create a variable. I’m gonna call it first part. This will be the first part of the sentence. I’m using let. Let is a variation on var. It’s essentially doing the same thing. There’s some slight variations. But we can use let pretty much how we would use var. So let, first part. In the value I’m storing in the variable, first part is going to be I am the beginning comma and a little space. And then I’m going to start doing some other things in this function as well. I’m gonna tell this function, second thing you’re gonna do is you’re gonna create another variable called second part. And the value I’m gonna store in there is going to be and I am the end of the sentence, exclamation point. And the last thing that I want this function to do is return first part. I’m gonna use plus. The plus are are the operator to concat these two sentences together. So first part plus second part is gonna return a one single string that should be I am the beginning comma space and I am the end of the sentence. 

Let’s take a look and see what we’ve got. I’m going to go ahead and start a Quokka on this val. Quokka is a VS code extension that is gonna help me take a look at some of the values of the variables on my file. It’s just really helpful to see what’s going on in the file. So I’m going to create a variable called result or more appropriately, full sentence. And what I’m gonna store in there is the result of invoking sentence maker. Sentence maker parentheses. Okay. I’m gonna type out the name of the variable for the sentence and Quokka is gonna tell me what value is being stored in full sentence. I am the beginning and I am the end of a sentence. So I’ve used a multi-line function here to be able to create a function that does multiple tasks and then returns a final value for us.

Multi-Line Functions – Practice II

Let’s take a look at another example. Function. Let’s call this dream maker because it’s going to create a dream for us or a wish for us. Let’s see here. This function will first off … Let’s start off with a number. So let num. And I’ll say 50. And then I will override the value of num by first referencing the variable name. Num. And I’m gonna say use the equal sign as an operator to override its value and say the new value for num will be num, which is currently 50 times two. So the new value for num should be 100. And then the final thing that I’m gonna do is return the string. I want to live until I am and then I’m going to concat on that number. And I’ll just put num. So this should give us the value. I want to live until I am 100. Let’s see if it has. I’ll say let result equals the invocation of dream maker. And let’s Quokka tell us what is being stored on result right now. I want to live until I am 100.

So this was just a quick dive into multi-line functions. Functions can do so many things for us. So realize that. Realize that you can tell functions to do multiple tasks. It can do one single thing or it can do 50 single things. It’s kind of up to you and your imagination and what you need your function to do for your program. 

Dynamic Functions in JavaScript

Let’s talk about creating dynamic functions in JavaScript. You’re gonna be creating a lot of different functions. And the functions you create are probably gonna be designed to perform a very specific task. But we want to be able to create dynamic functions. Functions that can be invoked and can perform a specific task but based on certain information that is passed into the function. Functions can have inputs and outputs. We’ve discussed outputs with or what a function can output with return statements. And let’s talk a little bit about making our functions more dynamic by discussing what inputs we can give to a function.

Dynamic Functions – Practice I

Let’s take a look at the code editor. And let’s create a function. I’m gonna call this function greeting. Now this function does one thing. It is going to return a string. It’s gonna say hello Joe. And what I’m gonna do is I’m going to capture the results. I’m going to say let result. And I’m going to invoke greeting. 

Okay. So like I said, functions have inputs and outputs. So when I invoke greeting, the output of this function is the string hello Joe. It’s returning that value. That’s its output. And that output gets stored in result. I’m gonna show that to you by kicking off Quokka. Quokka is just a VS code plug in to help us understand some of the values of our variables in this file. So if I type out the name of variable here, it’s gonna tell me what is stored inside that variable. Hello Joe. Okay. So we have this string hello Joe that is being stored in result. No matter how many times in invoke a greeting. Let’s do it again. Let result two equal greeting. Invoked again. And let’s take a look at the value of result two. No matter how many times I invoke this, I am going to get hello Joe every single time. 

This function is not very dynamic. So in order to make this function more dynamic, we have to be able to take in some sort of input into this function. And I’m gonna show you how to do that. So I’m gonna get rid of this second invocation and result two. Okay. If I wanted to pass a piece of information into this function, which we can do. We can give it an input. I’m gonna do it here. When I invoke greeting, I am going to in between these parentheses put a piece of information here. And I’m gonna pass greeting a specific name. I’m just actually gonna pass it in my name. Now, I’m passing in a string, Joe. And this string here, whatever I put in between these parentheses is called an argument. Okay? This is the function’s argument. 

And in order to capture this value that is getting passed into the function, I need to have a parameter. Parameters are placed in between the parentheses in the function definition. So because I’m passing in the name, I’m gonna call this parameter name. I can call a parameter whatever I want. It doesn’t matter what it is, but you should name it something appropriate to the type of data that’s getting passed into the function. So I’m passing in the string of Joe. And I’m capturing that value. Or that value is being stored in this parameter name. Now, parameters you can treat just like local variables in the function. So instead of hard coding Joe here. I am actually going to concat name onto the end of this string. Now if you take a look at what Quokka is showing us here. Inside this result variable, we’re still getting hello Joe. It’s the same exact result. Except this time, Joe was not inside of the function. It was not a part of that string to begin with. We passed that information in as an input to this function. 

So we made this function more dynamic by using this argument, the string Joe, and passing it into this function as an input. And we capture that value using a parameter. Parameters go between the parentheses and the function definition. And then we can use that parameter just like any other variable inside this function. So now we’re returning the string hello and we’re concating this variable onto the string here. 

You can see this … The value of result though. Quokka is telling us that the value of result is still hello Joe. Even though we’re no longer hard coding the string hello comma Joe. So now we’re actually taking in an input. But the cool thing about what we’ve changed, even though we’re getting the same exact result right now, is we’ve made this function dynamic by using arguments and parameters or using inputs. 

If I were to … I’ll say let result two. I’m gonna invoke greeting again. Except this time, I’m gonna pass in the string Nick. Let’s take a look at the value of result two. This time, result two is giving us the value of Hello Nick. And again, one more time, if I wanted to do it again, let result three equal greeting and pass in Greg. And now the value of result three is hello Greg. Okay? So we’re taking in an input and the function is returning a different string based on that input. Based on the argument that we passed into it. 

Dynamic Functions – Practice II

Let me show you another example where we’re gonna do a little bit of math. So I’m gonna create a function called multiply. And this function will actually take in two pieces of information. So I’m gonna put two parameters here. Num one comma num two. So you’re gonna separate each parameter with a comma. And then the curly brackets. And what I want is I want this function … It’s gonna take in two numbers. The inputs are gonna be the values of num one and num two. And then it’s going to return or give an output of num one times num two. Okay. Now when I invoke this function … Say let result and I’m going to invoke multiply. And what I’m gonna do here is pass in two arguments. I have two parameters. I can pass in two pieces of information here. So I’m gonna pass in three comma and five. Just like parameters, the arguments are gonna be separated by a comma.

Let’s take a look at what result it. Quokka is gonna tell us that result is 15. So I passed in three. This first argument gets passed into this first parameter, num one. And the second argument to the second parameter. And you can have as many arguments and parameters as you want here. If I wanted to have a third, fourth, and fifth parameter … Or excuse me. A third, fourth, and fifth argument, I would have to have a third, fourth, and fifth parameter to be able to catch that incoming value. Okay? But in this case, we just have two arguments. So we need two parameters. I’m taking in these two inputs three and five. Capturing them in num one num two. And then multiplying them together and returning that output. And the result is 15. 

So this is an introduction to inputs and outputs using arguments and parameters and then returning values outside of a function to create more dynamic functions in JavaScript. 

There will be times when you want some function to be invoked or perform some task when some event occurs. For example, when some user clicks on a button in your application, you may want some function to run. I’m gonna show you how to do that. Let’s take a look at this HTML file. 

So right now there is nothing in between our opening and closing body tags. I’m gonna change that. I’m gonna add in a button element. And in between the button tags I’m gonna put submit. Over here in the browser window, you can see our submit button. Right now I could click on it and it does nothing, but let’s change that. In order to change that, we’re going to need to use a little bit of JavaScript. I’m going to add script tags towards the end of the … Or right before the closing body tag. If I want to type valid JavaScript, I can type any valid JavaScript between script tags here. Okay? 

So first thing that I want to do in order to run some function when there is a click on this element is I need to use JavaScript to actually select this element. The way that I’m gonna do that is as follows. Let submit button be assigned the value of document.getElementById. And then I’m going to invoke it. Okay. So this reads a little bit just like English. Document.getElementById. I’m trying to select some element by its ID. So in order to do that, I actually need to have a unique ID on the element that I want selected on my submit button. So I’m gonna come up here to the button and I am going to add an ID attribute. And this is going to be a unique ID. And the value for this ID is going to be submit dash BTN. Okay. Now down here back to our JavaScript. Document.getElementById. If I wanted to retrieve some element by ID or select some element by an ID, I actually need to pass the ID in as an argument. So I’m telling it to go get the element with an ID of submit dash BTN. 

Alright. Now I have this variable here. Submit button. And I have that there because the result of Document.getElementById is going to be a reference to the element that got selected. Our submit button. So now that I have selected our submit button, I’m gonna reference the variable here on line 14. Submit button. And I’m going to do dot add event listener. And I’m going to invoke it. Okay. In JavaScript when we’re using add event listener, there are many different events that we can actually listen for. We are specifically just going to learn about using … We’re listening for a click event. 

The second argument directly after the string click is going to be a function. Now what we’ve got here is on our submit button, when a click occurs, this function will get invoked. And I’m gonna add an alert in here. Alert is a built in function in JavaScript. It will pop up a little alert window with whatever message we put in in between the parentheses. So I’m just gonna put submitted. Okay. I can put almost anything I want in this function. Functions can be very dynamic. But I’m just choosing just to do this one line submitted. Just so we can test out if this is working. I’m gonna come over to the browser window and click on the submit button. And our alert window pops up and says submitted. Perfect. It’s working. 

Let’s go ahead and recap one last time here. So what we have. The first thing we did is we use the Document.getElementById method to be able to select an element by its ID. So this string right here had to match some ID. And it matches our ID on our button element right here. In the submit button variable, we have stored a reference to our submit button. And we are referencing that variable and invoking add event listener. We are listening specifically for when a click event occurs on that button element. And when that click event occurs, the following function is invoked. 

Dynamic Functions – Practice III

Let’s go ahead and do one more example. I’m gonna add another button. And I know that I’m going to … I’m gonna call this my cancel button. But I know that I’m going to be selecting this button using some JavaScript. So I’m gonna add a unique ID. And the value of this ID is going to be cancel dash BTN. Now under our other JavaScript, I’m gonna follow the same exact pattern. First thing I need to do is be able to select this element so that I can listen for a click on it. So let cancel button be assigned the value of Document.getElementById. I invoke that method. And then I place the ID of the element I want selected in between the parentheses. Cancel dash BTN. Now that I’ve properly selected the element, I can listen for a click event. Cancel button as a reference to the variable on the line just above dot add event listener. And I invoke it. And the first argument we pass in is quotes click. We’re listening for whenever a click occurs on our cancel button. Comma function as the second argument. So this function will get invoked whenever there’s a click on our cancel button. And I’m gonna do something similar. An alert that says canceled.

Okay. So we have two buttons. And our two buttons, whenever they get clicked on, they should be invoking … Two separate functions should be getting invoked. One that alerts submitted and one that alerts canceled. Let’s go ahead and verify that that is occurring. Click on submit and we get submitted. Click on cancel and we get canceled. So that is one way that we can handle a click event whenever we click on a button and have a function be invoked.

[cta id=”589″ vid=”0″]

Further Reading

Intro to Objects – JavaScript 101

Intro to Conditionals – JavaScript 101

Intro to Operators – JavaScript 101

Related posts