When you think of the plus sign, chances are the first thing that comes to mind is math,
1 + 1 is
2, and that’s precisely the result that we get from the browser. But what if we tried to use the plus sign with a string? If we type
"John" + "Smith" what we get is a new string where the first and second ones are stuck together. In programming terms, we call this being stuck together concatenation. So “John” and “Smith” are concatenated together to make a new string.
Now, usually, I’d add a space between my first name and last name. So I have a couple of options. I could type + and then a space inside quotes, creating a new string that displays my name correctly. But I can also type my name with space and then + “Smith” which results in the same value.
Let’s turn back to numbers again for a second. What do you think would be the browser’s response if I type an equation, including the answer? In other words, if I type in
1 + 1 = 2. What do you think the browser will say?
x = 1, the single equal sign tells the browser that the variable named
x will point to the value 1 in memory.
Therefore, with an expression like 1 + 1 = 2, the interpreter is trying to set 1 + 1 equal to 2, and you can’t change the inherent value of what the expression of 1 + 1 is. It just doesn’t work that way.
1 + 1 === 2 with three equal signs, now we get back what’s called a Boolean value. Boolean means it’s either true or false. And
1 + 1 indeed does equal
2, so the value returned from this expression is true.
Knowing this now, we can use the power of the equal sign to start making our code seem like it’s making some decisions for us and using expressions to help provide control on how our code is executed.
Control Flow: Blocks
Now when we talk about control flow within the program, we’re referring to how the program executes and reads each line of code. Now sometimes, it doesn’t consistently run every line of code. Sometimes it skips some of those lines. And in doing that, that often gives the illusion that our program is thinking or making decisions. Now programs are built up of a fundamental building block of code called a block.
Let’s take a look at an elementary block first. So down here, I’ve created a variable and called it
name and set it equal to
Now let me show you something interesting about the
name variable. If I declare it again but give it a different value, what do you think will happen? So here I’ve added another
name variable, this time set it equal to
"Smith". And so when I save the page, let’s see what happens. We get an error because the identifier of
name for our variable has already been taken. And it’s already been taken because these two variables live within the same block. They’re within the same scope in the same block.
So, interestingly, what we can do is create separate blocks and then watch what happens. I’ve used the curly brackets to create a block around these two lines. And then the first
name declaration is outside that block. So when I press Save, will it show up with an error, print up John, or print up Smith? Well, let’s find out.
Since I declared the variables using the let keyword, it gives that variable a block scope. So it’s completely unaware of the variable that’s declared above it because that variable is only valid within this scope. So what do you think will happen if I move the console.log statement outside of that block? Now when I press Save, you got it, it prints up John.
So blocks group statements together and affect how variables are used. Now let’s see how a block is used inside an if statement or a conditional statement.
Control Flow: If Statements
Now let’s add a little bit of interactivity to the program. Let’s allow our program to make some decisions. We’ll do that with an if statement. This if statement, also known as a conditional, is set up to use the
if keyword. Then you put an expression between parentheses. After the parentheses, you create a block, so in the open curly brace, you have your statements within that block, and then you close it with a curly brace.
And, of course, it says “Hi John”. So what would happen if I changed the value of the name variable to “Smith”? When I save that change, nothing’s printed on the console because we haven’t told it to do anything if the name doesn’t equal “John”.
So let’s add that portion to our conditional statement. So now, in addition to the if keyword, we have the
else keyword. What else does is it gives us a block of code that can run when the original expression does not evaluate to true. Basically, this says, if the name variable does not equal “John”, then print this string on the console. So let’s save this change, and now we get our new message.
And if we go back and change name to equal “John” again, save that change, you can see that it goes back to saying “Hi John”.
Now you can take control of this even more. You can add as many if statements as you want and create a nesting. So if the first expression doesn’t evaluate as true, you can drop down to the next one and so on until it just goes into the else statement as we see here. Let me give you an example.
So now, instead of just a single if statement, I have
else if. This says in English that if the variable of name equals “John”, then say “Hi John”. But if it is “Paul”, says “Paul, is that you?”. And if it doesn’t say any of those, then say “Wait, where is John?”. So we can change the variable, set that to “Paul”, and there we have our message “Paul, is that you?” printed up in the console.
But if it’s a different name, then we get our default message of “Wait, where is John?” So by understanding the concepts of control flow and blocks, you can add a lot of interactivity to your programs. And so we’ve been using this little thing called log. This is actually a function, so in the next section we’ll talk about how you can create your own functions and how they all work.
This code works great here, but what if we want to use that greeting logic repeatedly in different places within a more extensive program? We could copy this code and place it in other spots within the program, but that creates a problem. If the logic changes or we find out we have a bug in our existing code, we need to change that in two spots. And trust me, I can tell you from experience; there are times when you will forget to update things in more than one location.
So we always want to try and not repeat ourselves when we’re writing code. One of the best ways to do that is to wrap up blocks of code like this inside a function. So to illustrate, let’s change the code just a little bit at a time so you can see how a function works. First, what we’ll do is wrap it inside a function declaration.
Now what I did is added the function keyword and gave our function a name. So here I called this
greet, which we can run repeatedly. It creates a container around these blocks of code.
Even though I already saved the file, you’ll notice nothing happened over here on the console. And that’s because this only declares the function. Now what we need to do is call the function. The way you call it is using its name, type the open and closed parentheses, and if it’s at the end of a statement, we’ll go ahead and add a semicolon. So what do you think will happen as I save the file?
That’s right, it says Hi John.
So the same logic that was run before is now run when we call the
greet function. So if I call it again, you could see that the same code is run two times and I get the same result twice.
Now, as my application grows, if I want to use the
greet logic, I can call this function from anywhere within the program, and the same lines of code will run each time I call the function. Now, this is a great start, but we can make this much more flexible. Next, we’ll look at being able to declare arguments to pass data into our function.
Passing Data into a Function
Now, it’s nice that all this logic is wrapped up for us, but it’s still pretty limited. We have this block of code that changes what will be logged out to the browser according to the name variable’s value, but there’s no real way to change it at this point. We can add an argument to our function so we can pass the value into the function.
Instead of declaring the name variable here inside the function, we can move it up into the function declaration. And now that that variable is declared within the function declaration, we can delete it from inside it. Now we have a function that wraps up the logic of looking at the name variable, and now we can pass in different values for the name as we call the function. So down here in greet, I can greet the first time I run it based on the name “John.” The second time I run it, I can run the same logic based on the value for “Paul.” And I can even run it a third time based on the name “Scott.” So now, when I save the file, what do you think will happen?
When the greet function is run and the value of “John” is passed in from the name variable, we get “Hi John” When “Paul” is passed in for the name, we get “Paul, is that you?” And for “Scott”, we get “Wait, where is John?”
By adding an argument to the function, it makes it much more flexible because now we can pass in data from the outside world and run the same logic against different values. And where things get interesting is instead of passing in hard‑coded strings to the function, we pass in variables. Instead of doing this, we could say, let
name = "John", and now we can pass in the name variable into the function, and there we get our greeting.
So within the application, as the name variable changes, we get the expected result.
Returning Data from a Function
Now that you’ve seen how to pass data into a function, let’s find out how you can get data out of a function. So I’ve simplified our greet function here and taken out all the logic just so that we can hone in on what it means to return data out of the function. To do that, we use the return keyword, and whatever follows the return keyword is what comes out of the function when you call it. So here, to keep things simple, I’ll add in the string “Hello.” So now, when I call the greet function, when I save it, nothing happens.
And the reason nothing happens is that all we’re doing in line 62 is calling the greet function, but it is now returning a value, so we need to do something with it. Instead of just calling it, let’s take what comes out of the function and set that equal to a variable.
So this line says, let the message variable be equal to whatever value returns as a result of running the greet function. So when we run this, the string “Hello” is set equal to the
message variable. We can now log out the contents of the
message, and as I save the file, you can see that “Hello” is printed up on the screen.
Now we have the same issue here. We don’t want to hardcode the return value of our function necessarily, so we could return the name variable as it’s passed into the function. Let’s consider “Mary” coming into the greet function. It sets the return value to the message variable, and then when console.log runs to print it out in the browser.
Let’s introduce our logic back into the function, and then you can see how powerful this can be. So here, the function is updated with our greeting logic again, with some exciting variations. Now, starting from the top, you’ll notice that I declared a variable named result. Now, this is a practice that I like to do anytime I’m creating a function that has to return a result. It’s always best to declare it at the top and give it a default value. Here I’m going with an empty string. Based on the if statements within my function, I know that the variable will get a new value, so I could start with an empty string, but then the last statement will return the result.
Now within my if blocks, instead of just calling
console.log based on the generated message, I’m setting results equal to those strings. So if the variable name equals “John,” the result gets the value of “Hi John” Just like if name equals “Paul,” the result variable receives the value of “Paul, is that you?” It is mighty because it opens up this logic, not just to
console.log. I could use the same greet function to log the result out to the console, yes, and print it up on the screen or use it in any other way within my program. So now, as I come down and call the greet function, I can pass in “John,” I get the result of that logic being returned out of the function, and then I can take that result set into the message variable and do whatever I want with it. In this case,
console.log. But here we’re dealing with what’s called in programming the Separation of Concerns. Let’s save it and see, we’ve got Hi John.
The greet function is only concerned about creating a greeting based on a name that comes in and nothing else. And to verify you can see it working, that’s with “Paul” we get the expected result.
So I can take this same information and group it together. As I look at this information, it all relates to me, and I’m a person, so I’ll create a new variable and call that
person variable is going to be an object literal. If you recall from earlier discussions, it creates a block for us, so inside this block, I can create properties for my object. Now I’ll start the first name property from my object, and instead of setting it equal to its value by using the equal sign, here I use a colon. And while since we’re at the end of the line, you might think we need a semicolon, as we declare object literal properties, we’ll use a comma instead. Now I can create my last name and finally my Twitter handle.
It becomes exciting because instead of dealing with the individual pieces of data for firstName, lastName, and twitter, I can use just the
person object. So when I pass person into
console.log, and we look at the browser console, you can see that it logs out an object to the console. And when I expand out the object there, I have individual properties for firstName, lastName, and twitter.
So what that means, if I want to target specific pieces of data within that object, I can use dot notation, so that would be person dot, and then I can access the firstName, lastName and twitter properties. And if you notice something cool, I also have statement completion within Visual Studio Code. So when I press that dot, it’ll show you the different properties associated with that object.
And it becomes even more interesting when we add some behaviour together with this data. So you remember our greet function from before? Well, we can add that in here as well. This time, instead of declaring a string, I can declare this property as a function. And inside the function, I can log out my greeting. And here I’ll say “My name is John”. Now inside the function, I have access to the properties of this object by using the
this keyword, but we’ll be able to use it here within this function for right now. So now I can come over and call that function directly off of my object. So when
person.greet() is run, I get the message of “My name is John”.
So as we implement Bethany’s Pie Shops, you’ll see objects a lot, especially when we call functions of other objects, just like you’re used to seeing under
So let’s take a look at this working here in the browser. Now, the way you declare an array or the way you create a list declares a variable and sets it equal to open and closed square brackets. This bracket notation is what tells the browser that you’re declaring a list or an array. So, let’s start working with a series of numbers. We can fill this list out by adding in values with commas between them. When we log the array out to the console, you can see that it shows us this list. I can expand the list; we can see the individual values within the array.
Arrays are pretty flexible. It doesn’t have to just work with numbers. In fact, you can do strings as well. So here I’ve created a list of names, and so when we save that, you can see that the array shows up with that same list of names.
But you can also mix different types of data within an array. In this example, I have a number, a Boolean value, and a string. And when we look at the result in the browser, you can see that the same values show up in their places inside that list, all being different types of data inside the array.
As you take a look at this list, you’ll notice some numbers associated with each value. Here, for the first one, it has 0, and then we have 1, and then 2. It means arrays are zero-indexed.
Now, I know that doesn’t make sense, so let me show you what I mean here. Right now, I’m passing the array variable into
console.log. But if I want to access the first value in the array, I can use the open and closed brackets and then pass in the index or value. So if I want 100, I can pass in 0, and now when I save that, it just returns the value for 100.
But once we have that array, once we have that list of values, there are all kinds of neat things that we can do with it. We can take those values and reverse them.
And you can even add and remove items from the array. So if I wanted to add something to this list, I could call the
push function, and so it returns for me the new length of the array, but I can also ask for it again. And there, I get the count of the items that are inside the array.
So what’s powerful about arrays is you have this list of data, and then inside your program, you can access each one at a time and do something interesting with them. But to do that, we need to use a loop, so we’ll look at loops next.
Have you ever heard the joke about how the guy got trapped in the shower? He was looking at the instructions on the shampoo bottle, and it read, you wash, rinse, repeat. Yeah, he never made it out. This set of instructions created a never-ending loop, and loops are powerful constructs for a programming language. They allow you to do what we call iterate or do something over and over again, and in context with our last discussion on arrays, you can iterate over lists of data as well.
Let’s start out simple and see what it looks like to work with your first loop. Now to use our loop we’ll implement some logic that does some counting for us. So let’s say we want some code that will count from 0 to 10. Well, we’ll start off by creating a couple variables to give us the starting point and the ending point.
Now when we think about what we want to do in terms of everyday English language, we want to keep counting while the value of your current count is less than the maximum. So you’ll count from 0, 1, 2, 3, 4, all the way up to 10, and you’ll do that while the current
count is less than the
while, which we can use to create this loop. While it takes an expression, and as long as it returns true, it will keep executing the block that is underneath the keyword. So we want it to keep processing while the count is less than the
max. As it runs, we want it to print out the current count, and then to make sure we don’t get stuck in the shower or inside an infinite loop, we need to make sure to increment the counter. So when we get to the end of this block, we want the count to equal whatever the count is, plus one more. When we save the file, you can see that it uses a loop to count from 0 to 9.
Now, if you recall from our conversation about arrays that are indexed at 0, this is doing the same thing. Our count starts with the value of 0. The block inside the loop executes ten times, so starting from 0, we go all the way to 9 by implementing the count by 1, 10 different times. While loops allow you to create a loop that repeats the exact instructions while an expression is true.
While loops are useful, you don’t see them as often as another type of loop, and that’s the
for loop. We’ll look at that next.
Picking up where we left off with the
while loop, I’d like to show you another loop called the
for loop. Now the for loop is a little more cryptic, and that’s because the syntax is a bit more compact, but the way it’s set up gives you a lot more flexibility in how you can work with objects and data inside the loop.
Here, let me show you what I mean. We declare variables outside the loop and manage the count’s value at the bottom of the loop with our
Let me paste in a
for loop and you can see that the syntax is different, but it still prints out the same result to the console window.
As we look at the anatomy of this loop, you’ll begin to recognize some of the same types of constructs present in the
while loop. So first, we have our counter. Usually, you’ll see for loops use a variable name of
i, to begin with. It generally stands for indexer or the index value of the loop. So it starts with an initial value of 0 for
Now the loop continues to iterate while the value of i is less than 10. As we’ve seen before with our
while loop, we had a variable called
max, and here, we’re just setting the maximum value explicitly to 10.
Now, each time the loop executes before it reruns the block, it increments the value of i. It is a new notation and is shorthand for saying i = i + 1.
Once again, the loop is initialized with a variable named
i, its default value is set to 0, it continues to run while the value of
i is less than 10, and every time it runs, it increments the value of
i by 1. So now, this loop is much more compact, and the indexer is readily available to us.
So how might we use a loop like this? Well, let’s take an array of numbers and see what that looks like. So this time, instead of telling the loop that we want it to run while
i is less than 10, rather what we’ll do is have it look at the length of our numbers array.
We can now use the double bracket notation to pass the index value into our array to get the individual value from the list.
Again, as this loop executes,
i is initialized to 0, it will continue running as long as
i is less than the length of our array, and in this case, that’s 3, and then each time it runs, the indexer or the
i value is incremented by 1. Each time it runs, we can use the value of
i to extract the number of the appropriate position.
So I’ll save the file, and here within the browser’s console window, you could see that it prints up 1, 2, and 3, and of course, that works on any array.
Now arrays have a function that makes working with loops even easier for array values, and that’s called for each, and we’ll look at that next.
forEach, and what it lets you iterate over the values of an array one by one. But the syntax is so much more straightforward than a
for loop and a
So here I have an array of day names, and so if I want to print something up for each one of those, I can start by calling the function
forEach off of the day’s array.
forEach is going to pass some values as arguments into my anonymous function. The first thing will be the data for each item on the list, so we’ll give this argument the name of the day. It also passes in the index value of the item within the array.
It is really handy, so we’re not left guessing what position in the array the value that comes in is within the array. So now we can use this to print up some information within the console window of the browser. So we’ll do
console.log. And now I’ll show you something new when you’re working with strings. Instead of just using quotation marks, I’ll use the backtick character. Now, this creates a template string that allows us to do something exciting. Here I want to print what the day is, so I’ll do
day: space, and now I want to get the value of the day variable and stick it into my string. I can do that simply by putting in the dollar sign and opening and closing curly brackets and then putting day right in there. I also want to show the index value, so I can do the same thing by grabbing the value of the variable index and placing it inside my string.
So as I save the file, you can see them over here on the console. I’ve got Monday at index 0, Tuesday at index 1, and Wednesday at index 2.
If you need any help or something is going wrong, let me know. It will be my pleasure to help you. If you want to extend some point, we have discussed, contact me so we can cover in the fllowing posts.
We also have pro bono projects just in case you are interested in learning more about them.
Be aware of why we started this project by clicking here.
Learn more about other posts here.
If you are a good reader like myself, I recommend the following readings:
- Docker Quick Start Guide: Learn Docker like a boss, and finally own your applications
- Docker for Developers: Develop and run your application with Docker containers using DevOps tools for continuous delivery
- Responsive Web Design with HTML5 and CSS: Develop future-proof responsive websites using the latest HTML5 and CSS techniques, 3rd Edition
See you in the next post!