Module 1: JavaScript Fundamentals
Overview
This module introduces you to the fundamentals of JavaScript programming. You'll learn about variables, data types, operators, and how to write basic JavaScript code.
Learning Objectives
- Understand JavaScript variables and data types
- Work with JavaScript operators
- Create and manipulate strings and numbers
- Understand basic program flow and execution
- Use console.log() for debugging
Working on a Web Application
Introduction
Welcome to your first core competency at BloomTech, and congratulations on taking the next step in your professional software engineer journey! Before we dive into learning Javascript, we are going to learn about some technologies and tools we will use throughout the course.
In an industry that can be so much in flux, it is important to have something stable, something that steadily grows no matter the circumstances, which is why we suggest, you always remain curious. Unlike many other professions, software engineering is a very dynamic field that may look very different from one job to the next, or from one person to the next, or even one day to the next.
In this reading, you will become familiar with the essential skills of opening and editing coding files. Step-by-step set-up instructions are provided so you have all the tools available to learn here at BloomTech. By the end of this segment, you will be able to:
- Open and access an HTML file
- Display said HTML file in Chrome
- Run some Javascript code in HTML file
- Configure additional settings in code editor
There is much to tackle here, so let's get started!
Here are some definition for terms you'll be seeing throughout this reading:
- HTML: HTML stands for Hyper Text Markup Language. This language is used to build webpage content.
- Javascript: Javascript is a language used in web development that adds functionality to a page, such as responding to clicks, bringing in data from outside sources, etc
- Chrome: Google Chrome is a popular browser that includes useful tools when building webpages. Built by Google.
- VSCode: VSCode is a coding program built by Microsoft, it is used for many purposes, including developing websites.
Pre-requisites
Make sure to complete orientation!
Case Study: Washington Community Center
Welcome to your first Case Study! Throughout Module 1, we will be working alongside a Community Center, Washington CC where you have been hired as a software engineering teacher. Throughout this module, there will be different tasks and different asks. Follow up with some practice and you will be one step closer to becoming a professional!
Lesson Plans:
You are drafting the lesson plans for the first week of classes, which will primarily expose some of the files and tools they will need for the remainder of the course. It is important to not only introduce them to a HTML file but also to show them how that file can be managed and manipulated in a code editor.
Opening your first web application
Overview
To kick off this core competency, let us first learn how to open an HTML file in Chrome and VSCode.
First, copy the following into a new file in your code editor, named "index.html".
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web App</title>
</head>
<body>
<h1>Hello, World</h1>
<script>
console.log("Here is a small program that runs on this page.");
</script>
</body>
</html>
This file contains some basic HTML code, better known as HTML "markup," that will display
the words "Hello, World" in any web browser. Make sure you note the location of where you download the file on
your computer.
Opening with Chrome
The Chrome web browser can render any HTML file and display it on the screen, just like any website. You can open the index.html file using your Chrome browser in two ways.
- You can locate the index.html file where you saved it on your computer, right-click on it, and specify to open it using Chrome.
- You can also open Chrome first and select "Open File" from the "File" menu at the top of the page. Locate your file and click "Open".
Opening with VSCode
The VSCode application will allow you to edit any HTML markup before being rendered by the Chrome browser. To open a file using VSCode, we recommend opening the VSCode application first. Usually, a "Get Started" page will appear, and you can select the option "Open". Navigate to your index.html file where you saved it on your computer. If this option does not appear, you can select "Open…" from the "File" menu at the top of the page and then navigate to your file. After doing so, you should see the following HTML markup for the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web App</title>
</head>
<body>
<h1>Hello, World</h1>
<script>
console.log("Here is a small program that runs on this page.");
</script>
</body>
</html>
Before continuing, double-check that you have enabled the "auto-save" feature by selecting it on the "File" menu at the top of the page. This feature will save your work each time there is a delay in your work or you focus away from the editor screen.
How to Build it
Under normal circumstances, we will review the content of what we have just learned by returning to the case study introduced at the beginning of this core competency. However, since some learning objectives early in this course are just a half-step towards the following learning objective—like this one— they will not have a "How To Build It" section. Please continue with the "Practice Problems" for this learning objective.
Practice Problems
Each learning objective has its own set of practice problems. These practice problems allow you to practice what you have just learned in the current learning objective.
Download the entire set of practice problems for the Sprint by clicking HERE. (You only need to do this once per sprint.)
For guidance on setting up and tackling practice problems, please watch this quick tutorial:
Walkthrough
Accessing the JavaScript interpreter: the console
Overview
The console is one of the most fundamental tools you will use when developing web applications. It is part of the Chrome browser and works like a log sheet. You can log, or print, any values from your code to the console by writing the following:
console.log("Here is a sample sentence to log.")
The console is also great at recording errors. If something doesn't add up in your code, the console will display the error and which part of your program the error originated from, also known as a "stack trace". Remember, an error= try again.
Finally, the console runs on Javascript; thus, if you want to test any Javascript code, you can type it directly into the console (one part at a time) and hit "Enter".
To access the console in Chrome, simply use the keyboard shortcut Cmd + Option + J on a Mac or Ctrl + Shift + J on Windows. When opened on our "index.html" file, it should appear on the right-hand side of the screen. Click to the right of the small blue greater-than sign ( >) to make the cursor appear. Then use the following command:
console.log("Hello World")
After pressing Return on a Mac or Enter on Windows, notice how our logged sentence printed out to the console on the line just below our console.log() command. You can ignore the undefined line just below it.
Adding code to a page using VS Code
Overview
Now, let's test how the index.html file we have loaded on our VSCode application is linked with the one rendered in our Chrome browser. If we edit anything in the VSCode (and save it!), and then refresh the page in our Chrome web browser, we should see those changes reflected on the page.
Let's add a new log command to our index.html file. Our old log command is between two lines with the label <script>. This location is critical. We must place any Javascript code we want to include in our web application between the two <script> labels. Since console.log() is a Javascript command, we will also place it between the <script> labels just below our existing one. Let's add console.log("This is my very first program!") like so:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web App</title>
</head>
<body>
<h1>Hello, World</h1>
<script>
console.log("Here is a small program that runs on this page.");
console.log("This is my very first program!")
</script>
</body>
</html>
If we save that in VSCode and then refresh the Chrome browser, we should see a new log statement appear in the console along with the old one.
How to Build it
Adding a Header
Let us take what we have learned from the last three learning objectives and put them together for the web development project you are building with your students at Washington CC. You decide that you are going to make things more engaging by using an index.html file that includes the header: "Available Clubs at Washington CC". Here is what that file would look like in a code editor:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Washington CC</title>
</head>
<body>
<h1>Available Clubs At Washington CC</h1>
<script>
</script>
</body>
</html>
Feel free to edit the index.html file you already downloaded, or create a new one if you would like to follow along.
Adding Club Information in Javascript
Eventually, you would like to create a page with all the clubs' meeting times and locations. Usually, Javascript will load information before sending it to the HTML page. Let's simulate this by logging the information about the Improv Club, the Chess Club, and the Glee Club within the HTML document's <script>.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Washington CC</title>
</head>
<body>
<h1>Available Clubs At Washington CC</h1>
<script>
console.log(
"The Improv Club meets every Tuesday and Thursday in the theater."
);
console.log(
"The Chess Club meets every Monday and Wednesday in Room 123."
);
console.log(
"The Glee Club meets every Monday, Wednesday, and Friday in Room 321."
);
</script>
</body>
</html>
If we open our file in the Chrome browser, we should see all three of these clubs printed to the console.
Walkthrough
Using the console to troubleshoot problems
Overview
The console is an excellent tool for tracking errors. Javascript will record most technical errors in the console. To demonstrate how the console can track these technical errors, we can try using the console.log() command again, but capitalizing the C of console:
When doing this, we get an Reference Error: Console is not defined. This error tells us that the word, Console, that we tried to use hasn't been defined yet, i.e., it doesn't exist. Because words entered into Javascript are case-sensitive, Console.log() with a capital C doesn't equate to our pre-existing command console.log(). Javascript can't read it, so it throws an error.
How to Build it
At Washington Community Center, you would like to introduce your students to a few errors early, without telling them why they were caused. Continuing your list of clubs in the console, you then log the information for the Debate Club, but do not include the quotation marks. Here is how that would look:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Washington CC</title>
</head>
<body>
<h1>Available Clubs At Washington CC</h1>
<script>
console.log(
"The Improv Club meets every Tuesday and Thursday in the theater."
);
console.log(
"The Chess Club meets every Monday and Wednesday in Room 123."
);
console.log(
"The Glee Club meets every Monday, Wednesday, and Friday in Room 321."
);
console.log(The Debate Club will meet every Monday, no Tuesday, no Monday.)
</script>
</body>
</html>
This mistake would cause a Syntax Error and suggests it is missing a closed parenthesis ). This is a good suggestion by the console, but we know the issue is that it is missing quotation marks. This is a good example of when the console might be off when suggesting a fix, but still gives us enough information to point us in the right direction of what went wrong.
Walkthrough
Adding comments to the code
Overview
One of the most valuable programming language features is the ability to write comments alongside your code. Comments are written notes by the developer that exist in the code write-up but do not get read when the program runs.
Developers use comments as notes for either themselves or other developers. Comments can be directions or clarifications for other developers who might have trouble interpreting the code. Comments can also be personal notes that a developer might make when debugging code. Or, and this is very common, comments might be code that is not being used now, but is important enough to keep around in case future circumstances call for it.
To write one-line comments in Javascript, we add two slashes // before any text that you want to include as a comment, better known as "comment out", as in:
console.log("Hello, World") // prints out "Hello, World"
The comment above, // prints out "Hello, World", lets us know that Hello, World will print out to the console, but it won't actually be run by the program.
Side note, in VSCode, you can also use a keyboard shortcut Command + / on a Mac to add double slashes, //, or Ctrl + / on Windows to a line; or you can highlight several lines you want to comment out and press Command + K + C on a Mac or Ctrl + K + C on Windows.
How to Build it
Commenting on Undecided Clubs
Let's return to your work on crafting the website you are building with your students that will display all the active clubs at Washington CC. Let's continue by adding a few more clubs, ASB (Associated Student Body) and the math club; but since these clubs still need to decide on location and times, we will comment them out for now. Here is how that would look:
<head>
<title>Washington CC</title>
</head>
<body>
<h1>Available Clubs At Washington CC</h1>
<script>
console.log(
"The Improv Club meets every Tuesday and Thursday in the theater."
);
console.log(
"The Chess Club meets every Monday and Wednesday in Room 123."
);
console.log(
"The Glee Club meets every Monday, Wednesday, and Friday in Room 321."
);
console.log(
"The debate club will meet every Monday, no Tuesday, no Monday."
);
// console.log("ASB will meet...")
// console.log("The Math Club will meet...")
</script>
</body>
</html>
Notice the double slashes // before the last two logs, which commented out those lines.
Commenting on Club Presidents
Furthermore, you would also like to keep track of the president's name for each club; however, since you do not care to display the name on the website, you decide to include the president's name as a comment instead. Here is how we could do that:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Washington CC</title>
</head>
<body>
<h1>Available Clubs At Washington CC</h1>
<script>
console.log(
"The Improv Club meets every Tuesday and Thursday in the theater."
); // President: Wayne Brady
console.log(
"The Chess Club meets every Monday and Wednesday in Room 123."
); // President: Magnus Carlsen
console.log(
"The Glee Club meets every Monday, Wednesday, and Friday in Room 321."
); // President: Lea Michele
console.log(
"The debate club will meet every Monday, no Tuesday, no Monday."
); // President: undecided
// console.log("ASB will meet...")
// console.log("The Math Club will meet...")
</script>
</body>
</html>
Notice how our comments can be on the same line as the code the browser will read.
Walkthrough
Formatting code automatically
Overview
When a browser reads code, it will read it character-by-character and line-by-line and disregard spaces or indentations. However, formatting code to include spaces and indentations makes it more readable to you and other developers. Luckily, VSCode has a built-in feature that automatically formats your code when it saves a file. Understanding what this format looks like is not necessary to memorize. With auto-formatting, how things get placed will become more familiar as time goes on.
Here is an example of a really poorly formatted version of the index.html we have been working on:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web App</title>
</head>
<body>
<h1>Hello, World</h1>
<script>
console.log("Here is a small program that runs on this page.");
console.log("This is my very first program!");
</script>
</body>
</html>
And after saving this file with the auto-format feature enabled, we get a much more readable, organized look:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web App</title>
</head>
<body>
<h1>Hello, World</h1>
<script>
console.log("Here is a small program that runs on this page.");
console.log("This is my very first program!");
</script>
</body>
</html>
One final note: sometimes, when you save a file and expect it to auto-format, it doesn't. This can seem puzzling at first, but this usually means you have an error in your code, and the auto-format feature can't figure out where to place everything if there are errors on the page. First, find and fix the error, and then the auto-format feature should work again.
Walkthrough
Conclusion
In this core competency, we introduced a lot of the tools, and some tricks of the trade software developers use on daily web applications. We first learned how to open HTML files with the Chrome browser, and how to edit those files in VSCode. We practiced logging information in the console and understanding different scenarios for why that would be important. We also practiced making comments in Javascript and discussed why those are important to a developer's everyday life.
This first core competency will feel slightly different from the rest. It introduces a lot of add-ons, without getting into much of the nuts and bolts of Javascript. If you need help understanding the need for some of these add-ons, their value will only become more evident as we embark on actual Javascript content in the following core competency.
Values
Introduction
Boiled down to its simplest parts, Javascript is all about values: creating them, storing them, updating them, moving them, utilizing them, and even, forgetting them.
They are much like the cells of the human body, each having their own identity and purpose. But, when you get enough of them together performing the same function as muscle cells would pump blood in the heart, they take on a newer, more prominent sense of purpose that can make an application shine. Though, in the end, if you break it down, all that remains are values.
There are many different types of values used in Javascript, each with their own pros and cons, all of which we will cover in due time.
In this reading, we will focus on some of the most fundamental values, better known as primitive types, and introduce some ways we can use them.
Pre-requisites
Exposure to the Console
Case Study:
What is web development without Javascript, the language that controls the logic of it all? It is time for us to return to the project you are creating for your software engineering students at Washington Community Center. So far, you have done great work setting up the HTML file your students will use to start building their school's website on available clubs and logging the information for some of those clubs in the console. Now it is time to work with some of the value types needed for this project: strings, numbers, booleans, and even, undefined.
Walkthrough
Using arithmetic operators
Overview
Most web applications do not require heavy math skills, but basic arithmetic is almost always needed. Most of the logic and symbols used for mathematical expressions in Javascript is the same as you expect to see on paper.
Here are some commonly used arithmetic operations:
Arithmetic Operations Chart
Operation: +, -, *, /, **, %
Description: Addition, Subtraction, Multiplication, Division, Exponentiation, Remainder
And here are some examples of how these arithmetic operations might be employed:
2 + 3 // expression that evaluates to number 5.
1 + 2 + 3 // another longer expression evaluating to number 6
5 - 6.5 // this expression evaluates to number -1.5 (minus one point five)
2 * 3 // using the multiplication operator, this expression evaluates to number 6
10 / 2 // evaluates to number 5
10 / 3 // evaluates to number 3.3333333333333335
3**3 // evaluates to 27. The double asterisk, "**", is the exponential operator. 3 * 3 * 3 = 27
16 % 5 // evaluates to 1. The '%' symbol returns the remainder of the two numbers divided. 16/5 = 3, with a remainder of 1.
Remember that the console in your Chrome browser runs on Javascript. If you try any of these expressions in your console, you should expect to see some answers!
How to Build it
Similar to what we did in the previous section, you hope to plan for some of the mathematical expressions you and your students expect to see in your web application.
A possible feature involving a mathematical expression is "club capacity". You would like to show a capacity bar for each club that shows how full the club is of current members at a given time. Here is how that would look.
You would first need to set up an expression using a division operator:
Current Members / Total Capacity
For example:
8 / 25 // evaluates to 0.32
You would then need to convert that number into a percent by using the multiplication operator, like so:
0.32 * 100 // evaluates to 32
This is the final number, added with a "%" sign that you could include next to each listed club on the website. Ideally, when a member is added or dropped, the Javascript code will re-run and a new percent would be displayed.
Walkthrough
Joining strings with the + operator
Overview
As we continue along with the course, we will learn dozens of ways to manipulate strings. Among them is the "+" operator, which joins or "concatenates" two strings together. Much like in math, where a "+" operator is used to add a number, when used with strings, we can also say that the two strings are being added together. This is an extremely common operator to use when working with strings.
Here are some examples:
"String One" + "String Two" // expression evaluates to "StringOneStringTwo"; note that no space between the two strings was added
"String One " + "String Two" // expression evaluates to "StringOne StringTwo" a space was added between both strings because it was included in the first string.
"StringOne" + " " + "StringTwo" // expression also evaluates to "StringOne StringTwo" but added the space between the strings as its own string
In some cases you can also use the "+" operator to combine different types of primitive values, but this is rare and often discouraged.
Here is an example:
5 + "" // evaluates to the string '5'. It's one way to turn numbers into strings. Converting between types is often called "casting".
"Number" + 5 // evaluates to the string: 'Number5'. Other, more rigid programming languages would throw an error instead.
How to Build it
Let us return to our case study on the website you are building with the students of Washington Community Center. Remember that we determined that each listed club would have three separate strings of information: a club name, meeting dates, and a meeting location. Similar to what you logged in the console earlier, we would like to display each of these in one simple sentence for students to read. We can use the "+" operator to concatenate these three strings together. Here is how that would look with a few clubs:
"The Improv Club" + " meets every" + " Tuesday and Thursday" + " in the Theater" // will result to: "The Improv Club meets every Tuesday and Thursday in the Theater"
"The Chess Club" + " meets every" + " Monday and Wednesday" + " in Room 123" // will result to "The Chess Club meets every Monday and Wednesday in Room 123"
"The Glee Club" + " meets every" + " Monday, Wednesday, and Friday" + " in Room 321" // will result to "The Glee Club meets every Monday, Wednesday, and Friday in Room 321"
Walkthrough
Determining type with the typeof operator
Overview
More often than not, determining the type of a value is obvious: 24 is a number, "String" is a string, etc. But, there are situations when the type of a value may not be so obvious. Luckily, we have the typeof operator. The "typeof" operator, when placed before a value, returns the data type of that value.
Here are some examples:
typeof 'I am a sentence.' // prints 'string'
typeof "Washington CC" // prints 'string'
typeof 24 // prints 'number'
typeof "25" // prints 'string'. It may look like a number, but notice those quotes!
typeof undefined // prints 'undefined'
typeof "" // an empty string is still a 'string'!
How to Build it
You would not like to show your students this useful tool with some of the values you expect to encounter when building your web application. You ask your students to type in each one in the console preceded by the typeof operator to confirm their value types.
Here are some examples:
typeof "The Improv Club" // prints 'string'
typeof 'Monday and Wednesday' // prints 'string'
typeof 8 // prints 'number'
typeof 8/25 // prints NaN
typeof (8/25) // prints 'number'
typeof undefined // prints 'undefined'
Walkthrough
Conclusion
In this core competency, we learned about Javascript's most fundamental building block: value. We learned about different primitive value types, such as numbers, strings, booleans, even undefined values, and how to check the type of any value using the typeof operator. We also learned how to modify those values with arithmetic operators. Finally, we learned how to concatenate and combine strings together with the "+" operator. This was our first dabble with fundamental Javascript. Values will only seem more understandable as they are given more and more context.
Variables
Introduction
In our last core competency, we discussed how the nuts and bolts of web development work with values. But using values only as standalone items would require a developer to edit code each time a user wanted to change anything on the website, like changing one's status on a profile page. Thus, perhaps the most convenient thing you can do with values is to store them where they can be easily accessed and modified in other parts of the program.
In Javascript, any value type can be stored in something called a variable. Think of a variable as a type of container, specifically a food container. A food container can be manufactured and continue to exist without food; so can variables without values. But the intention of manufacturing food containers is to hold food, same with variables and values. Furthermore, some food containers are designed for one-time use, like zip-lock bags (mostly). Other food containers, like tupperware, are designed to be used multiple times for multiple types of food. In the same way, we have variables in Javascript that can only hold one value, period. While others are designed to hold multiple values at once, and even others are designed to hold multiple values too, albeit one at a time.
In this reading, you will learn how to create variables in Javascript and how to give those variables values. You will also learn which types of variables can be changed and how to go about changing them.
Pre-requisites
Primitive Values
Case Study: Washington CC Clubs
We are embarking on the third leg of our case study where you are a recently hired software engineering teacher at Washington Community Center. You and your students have been putting the early touches on your new web application that will eventually list all the current student clubs at Washington CC and information about each club's meeting times and location, as well as, member capacity. We have done a deep dive into exploring the types of values that we would expect to see when developing such a project: strings, numbers, booleans, and even, undefined values. It is now time to finally make those values more accessible to the rest of the application by storing them in variables that can either be referenced later or updated.
Walkthrough
Declaring a variable with let
Overview
Declaring let Variables and Assigning Them Values
Some variables are purposely designed to hold values that may change, or update, over time. We create, better known as "declare", these variables by using the keyword let in front of the name you want to use for your variable. Here is how you would declare a variable using let and assign it a number value:
let myNumber = 45 // noticed keyword "let" followed by a variable name, an equal sign, and the value
Notice above we first have the required let keyword followed by the name of the variable, which is entirely up to you. These two parts are all you need to declare the variable. If you then want to immediately assign that variable a value, then you would include the equal sign, =, followed by the value itself. In the example above, we have a number value, but you can assign any type of value to a variable. Here are a few more examples with other value types:
let sampleWord = "Washington" // variable assigned to a string
let sampleSentence = "I am a sample sentence." // variable assigned to another string
let currentValue = undefined // variable assigned to an "undefined" value
let isOpen = false // variable assigned to a boolean value
Declaring let Variables without Values
As mentioned before, declaring a variable using let only requires the let keyword and the variable name. Sometimes, it is useful to only declare a variable and not immediately assign it a value, like so:
let sampleWord
You can then later assign that variable a value by using the variable name followed by the equal sign, =, and the value itself, as in:
sampleWord = "Washington"
Notice how we did not include the let keyword here. Once the variable has already been declared, there is no reason to use let again for that same variable.
Variables that have been declared with let, can be reassigned values in the same way:
sampleWord = "Pumpkin"
Now, whenever the variable sampleWord is referenced, it no longer has the value of Washington, it has the value of Pumpkin.
Updating Values To let Variables
You can also reassign variables to themselves and add something more. This is particularly common with numbers, if you wanted to reassign a variable to its same value but, let's say, add one more. For example:
let myNumber = 45 // declaring variable "myNumber" and assigning it to a value of 45
myNumber = myNumber + 1 // "myNumber" now has a value of 46
You can also do this with strings:
let myString = "My favorite food is "
myString = myString + "pizza." // "myString" now has a value of "My favorite food is pizza."
Returning back to numbers, there is also a very commonly used shortcut to add one or more to a value, or subtract. You would simply state the variable name then add += to add, or -= to subtract, followed by the value you would like to add or subtract. Here are some examples:
let myNumber = 45
myNumber += 5 // adds the value of "myNumber" by 5 to 50
let myNumber = 45
myNumber -= 5 // subtracts the value of "myNumber" by 5 to 40
And finally, if you are looking to just add or subtract one to your number value, there is even a shorter shortcut that uses the operator ++ to add, or -- to subtract:
let myNumber = 45
myNumber++ // adds one to the value of "myNumber"; now equals 46
Redeclaring Variables
One last important note. You can not redeclare a variable within the same block of code.
let myString = "This Works."
let myString = "This Fails." // declaring "myString" twice will result in an error
If this happens, you can either choose a different variable name to declare, or omit the keyword let and then you would be reassigning that variable to a new value.
How to Build it
Let's return to our case study where you are in the middle of planning out the early steps to a website with your students at Washington CC. It is time we consider which values in our website will need to be stored in let variables.
One value, the most obvious one, is the number of members each club currently has. Your most resourceful students have just informed you that the improv club currently has 8 members, the chess club has 16 members, and the glee club has 22 members. Here is what that might look like:
let improvMemberCount = 8
let chessMemberCount = 16
let gleeMemberCount = 22
Well done, but shortly after guiding your class through declaring these variables, you have just received word that the improv club has added two members, and the glee club has lost four members. Updating those values would require either of the the following formats:
improvMemberCount = improvMemberCount + 2 // reassign value of "improvMemberCount" to two more
gleeMemberCount -= 4 // reassign value of "gleeMemberCount" to four less
A second value that we should store in a let variable is one we referred to earlier when we were speculating possible boolean values this application might need. Perhaps it would be a nice feature if presidents of each club could toggle their club between active and inactive, in case there was a stretch of the school year when the club couldn't meet. This feature could be controlled by a simple boolean value that can switch between true and false. With this ongoing change we will need to use a let variable to store this value:
let isActive = true // declaring a variable "isActive" and assigning it a boolean value of "true"
Now whenever a president of a club wants to make their club inactive, they can click a button that would then trigger the following:
isActive = false
In turn, this would prevent students from seeing the club among the active clubs list.
Walkthrough
Declaring a variable with const
Overview
In addition to let, variables can be declared using the keyword const followed by the variable name. As the name implies, a variable that has been declared with the keyword const, short for "constant", can not be changed. And since it can not be changed, it must be assigned a value when the variable is declared.
const myNumber = 45 // assigning a constant variable to the value 45
const sampleWord = "Washington" // assigning a constant variable to the value of "Washington"
To reiterate, if we were to try and reassign a value for one of these constants, as in:
const myNumber = 45 // declaring a const variable
myNumber = 46 // reassigning value, throws error
…we would receive a Type Error because the type of variable we are trying to change is a constant and can not be changed by definition.
The same rule applies when using shortcuts to add values to numbers, as in:
const myNumber = 45
myNumber++ // will still throw an error because myNumber is being changed.
To get around this problem, you would have to declare another variable to save that new value:
const myNumber = 45
const newNumber = myNumber++
Including const variables can be necessary for a program that needs to save important, unchanging values to a variable but wants to avoid accidentally changing those values later. This is actually a more common mistake than you might think, as many different components of programs could be worked on simultaneously by different developers who are all creating variables with names that describe similar values, like num for "number", or userName for a user's name.
How to Build it
Let us continue working on the web application you are building with your students at Washington CC. You just got out of a staff meeting during which you were notified that, for safety reasons, all student clubs could only have a maximum of 25 students. Knowing that this number will not change from club to club, this would be an excellent opportunity for a const variable:
const maxStudentCount = 25
The upside to declaring a const variable here is that it would prevent the future possibility of changing the maximum capacity of students for each club, so long as this variable is used where it needs to be.
For example, let's now return to the math expression we previously created to calculate our club capacity:
Current Members / Total Capacity
In the last "How To Build It" section, we created a variable to hold the ever-fluctuating numbers of members in our three trial clubs:
let improvMemberCount = 8
let chessMemberCount = 16
let gleeMemberCount = 22
Let us use just the Improv Club as an example. We can now take the improvMemberCount variable and divide it by the maxStudentCountvariable for this math expression:
let improvMemberCount = 8
const maxStudentCount = 25
improvMemberCount / maxStudentCount * 100 // evaluates to 32, as in 32% capacity
And now, if we were to update the number of members of the Improv Class to two more, we can reassign its variable to a value that is two more:
let improvMemberCount = 8
const maxStudentCount = 25
improvMemberCount += 2
improvMemberCount / maxStudentCount * 100 // now evaluates to 40, as in "40% capacity"
Walkthrough
Printing variables to the console
Overview
If at any point in the program, we need to know what value is stored inside a variable, we can use console.log() to print the value to the console.
const myNumber = 45
console.log(myNumber) // prints 45
This can be a very useful tool to keep track of which values your variables have at any point in your program, much like a checkpoint. If the values you print are what you expect, then it is a good indicator that you are still in control of how you are managing information in your program. This strategy is a very common practice used by developers; otherwise, you will be writing your entire program blind and hoping that it all works in the end.
Here is a quick example. Let's say we wanted to combine a first and last name for specific parts of our program. We might have something like this:
let firstName = "Sophia" // declaring first name variable and assigning value of "Sophia"
let lastName = "Papadopoulos" // declaring last name variable and assigning value of "Sophia"
let fullName = firstName + lastName // concatenating values of first and last name variable
console.log(fullName) // prints "SophiaPapadopoulos"
This is a great example of why you would want to use console.log() to check the values of your variable before continuing. By checking the value of fullName we can see that we did not include a space between the first and last names, as we might expect. In this case, we could change our fullName value to the following:
let fullName = firstName + " " + lastName // concatenating values of first and last name variable
console.log(fullName) // now prints "Sophia Papadopoulos"
How to Build it
In our previous "How To Build It" section we utilized some of our newly declared variables to calculate the member capacity of the improv club. We understood that the current number of members for each club changes, and thus was first declared with the keyword let.
Here is where we left off:
let improvMemberCount = 8
const maxStudentCount = 25
improvMemberCount += 2
improvMemberCount / maxStudentCount * 100
At this point, without logging anything to the console, we would have no idea whether our code actually performed the way we would expect. To check our work here, lets log the value of improvMemberCount both before and after two members were added, like so:
let improvMemberCount = 8
const maxStudentCount = 25
console.log(improvMemberCount) // prints 8
improvMemberCount += 2
console.log(improvMemberCount) // now prints 10
By logging these values to the console, we can ensure that our code is executing as expected. And if at any point something didn't add up, say, the second log still printed 8, we could more easily find the problem and fix it.
Finally, wouldn't it also be nice to determine if the math expression we used to calculate the current capacity works too? To do this, we can simply save that math expression in its own variable using let or const, and the printing that variable to the console too:
const currentCapacity = improvMemberCount / maxStudentCount * 100
console.log(currentCapacity) // prints 40, as in 40% capacity
Walkthrough
Conclusion
In this core competency, we learned about two different ways to declare a variable, using let or const. Remember that let allows us to reassign a value to that variable later in the program, but const does not, and requires a value to be assigned when declared. We also learned how to log variables to the console, and, thus, their values. Storing values to variables we can then call later in a program is essential to keeping track of our values, sorting them, and updating them, which we will see more of in future readings.
Stay sharp, stay curious, and remember, if you happen to use variables incorrectly, the console will kindly let you know.
Comparison and Logic
Introduction
A typical tool career counselors give to their clients is an aptitude test, or skills test, which gives them some indication of which career fields their client might initially find success in. Inevitably, these tests utilize a lot of comparative logic: "if this… then that" or "if this and this… then that instead", and so on. Comparative expressions such as these, help construct a profile of an individual's strengths and weaknesses and then determine some best-fit careers based on that profile. For example, if a person tests at a high level in interpersonal skills but low in analysis, then they might suggest a teacher but not a psychologist; whereas, if a person tests well in mathematics but not leadership, then they might suggest an engineer, but not a project manager.
Although an aptitude test like this is an obvious example of something that uses comparative logic, you will find that every program that you develop will need comparative logic to function.
This reading will cover all the fundamental operators used to make logical comparisons of values in Javascript, and how we can combine multiple operators to build more complex comparisons.
Pre-requisites
Primitive Values
Case Study: Washington CC
It is our final case study involving your role as a software engineering instructor at Washington CC. You have spent quite a few days introducing your students to the important tools, values, and variables you will use when developing your website on active clubs found at the school. We have already encountered a few scenarios, such as determining when a user is logged in and whether a club has reached its total member capacity. These would be good candidates to introduce comparative logic, and we will see how this works in the upcoming learning objectives.
Mastering the comparison operators
Overview
Comparison operators are used to compare two values to determine whether a condition is true or false. Here are the most commonly used comparison operators:
Strict Equal ===
5 === 5 // true
5 === 3 + 3 // false
"JavaScript" === "JavaScript" // true
" hello " === "hello" // false, whitespace matters!
"hello " + "world" === "hello world" // true
Strict Not Equal !==
5 !== 5 // false
5 !== "5" // true
"Hello World" !== "hello world" // true, case matters!
"" !== '' // false, single quotes and double quotes work the same
Greater Than >, Less Than << /h4>
5 > 4 // true
5 > 4 + 1 // false
4 < 5 // true
1 + 1 < 2 // false
Greater Than Or Equal >=, Less Than Or Equal <=< /h4>
5 >= 5 // true
1 >= -100 // true
-100 >= 100 // false
1 <= 1 // true
5 > 4 // true
5 > 4 + 1 // false
4 < 5 // true
1 + 1 < 2 // false
5 >= 5 // true
1 >= -100 // true
-100 >= 100 // false
1 <= 1 // true
In the grand scheme, it is essential to remember that these conditions will almost always trigger separate actions by the program depending on whether the condition is true or false. If a website only wants to show specific content to logged-in users, the site will check if the user is logged in to determine what to display. If a user wants to see only emails from a specific individual, the site will check each email to see if the sender matches the given email address.
As a side note, there also exists a loose equal operator with only two equal signs == instead of three, but it comes with behaviors you might not expect. Please avoid using this operator for now.
How to Build it
Let us return to the web application you are developing with your students at Washington CC. You noticed in your earlier work that your website would use a boolean value for whether a student was logged in. This logged-in value will determine if students should access different site features, like joining a club.
Let's create a simple comparison that will render true or false depending on whether a student is logged in:
isStudentLoggedIn === true // might be true or false depending on if a student is logged in
In this example, we used the pre-existing variable name isStudentLoggedIn and assigned it a value of true.
Another example of where we could use some comparative logic is with our member capacity calculator for each club. Let us say that we would like to ultimately change the color of the capacity bar to red if the capacity reaches more than twenty members out of twenty-five. We will save our red styling for a later time, but here is how the comparative logic would work:
improvMemberCount > 20 // true or false depending on if members are greater than or less than/equal to 20
Walkthrough
Solving logical expressions
Overview
It is common for one condition to require multiple, smaller conditions, each with their own comparisons of different values.
When faced with complicated decision trees in Javascript, we can resolve these problems by connecting conditional statements using two specialized operators to separate each logical expression:
The "AND" operator, &&, in which BOTH expressions must be true for the entire condition to be true.
(1 < 2) && (2 < 3) // true, because both sides of the && are true
(1 < 2) && (2 === 3) // false, because one side of the && is false
(1 < 2) && ('7' === 7) // false, because one side of the && is false
false && true // false, because one side of the && is false
(7 !== '7') && (100 !== -100) // true
(2 <= 2) && (3 < 4) // true
The "OR" operator, ||, in which only ONE expression must be true for the entire condition to be true.
(2 > 3) || (4 > 2) // true, because one side of the || is true
true || false // true, because one side of the || is true
false || true // true, because one side of the || is true
('Java' === 'JavaScript') || (7 === '7') // false, because both sides of the || are false
(5 >= -100) || false // true, because the left side of the || is true
As you can see from these examples, we can create conditions that involve multiple comparisons of entirely different values that will return a single boolean value, true or false, for the whole thing.
One final thing worth noting here concerns how we write these conditions. The parenthesis around each expression, as seen above, is optional. Removing them would not hamper the program's ability to run correctly, but including them is easier for developers to read and are commonly used.
How to Build it
As we continue developing our application for active clubs at Washington CC, we can find valuable ways to include some multi-part conditional statements. Take, for instance, the logged-in logical comparison we established in the last "How To Build It" section. What if we wanted to provide even more features specifically for club presidents, like editing club information? Of course, we still want to ensure that the student is logged in, but now, let's add another condition where the student has to be logged in and be the president. Checking these conditions would be a great use of our "AND" operator, &&, and could look something like this:
isStudentLoggedIn && isStudentRolePresident // true only if both are true
Let us return to our member capacity calculator. Checking capacity and notifying users if it's full is an excellent opportunity to add an "OR" operator, ||. Let's say we wanted the capacity bar to disappear if the club is full of members or has been marked inactive. Here is how the comparative logic of that scenario might look for the improv club:
(improvMemberCount === 25) || (isImprovClubActive === false)
As we can see in this conditional statement, if either the number of members of the improv club is at total capacity (25) or the club is not active, this condition will render true. Else, it would render false.
Walkthrough
Conclusion
This core competency taught us how to apply comparative logic to our values and variables. We learned that using comparative operators, like === or >=, can, in turn, tell us whether a condition is true or false. We also learned that real applications can be pretty complex in comparative logic and would need some version comparing multiple conditions using the && and || operators. It might be best to think of complex comparative logic much like a decision tree. If you feel overwhelmed by any of it, try mapping out your logic in a decision tree before applying it to Javascript. And remember, you always have the help of your instructors and peers should you need it.
Lesson Content
JavaScript Basics
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the web.
Variables and Data Types
JavaScript has several data types:
- String: Text values like "Hello World"
- Number: Numeric values like 42 or 3.14
- Boolean: true or false
- Null: Intentional absence of value
- Undefined: Variables that have been declared but not assigned
- Object: Collections of related data
Code Examples
// Variables let name = "John"; const age = 30; var isStudent = true; // Basic operations let x = 10; let y = 5; console.log(x + y); // Addition: 15 console.log(x - y); // Subtraction: 5 console.log(x * y); // Multiplication: 50 console.log(x / y); // Division: 2 // String operations let firstName = "Jane"; let lastName = "Doe"; let fullName = firstName + " " + lastName; console.log(fullName); // "Jane Doe"
Practice Exercises
Try these exercises to reinforce your understanding of JavaScript fundamentals:
- Create variables for your name, age, and whether you are a student.
- Calculate and log the area of a rectangle with variables for length and width.
- Concatenate your first and last name with a space in between.
- Convert a temperature from Celsius to Fahrenheit using variables.
Exercise 1: Variables
Create variables for your name, age, and student status:
// Type your code here let name = ""; let age = 0; let isStudent = false; // Display your variables console.log("Name:", name); console.log("Age:", age); console.log("Student status:", isStudent);
Exercise 2: Rectangle Area
Calculate the area of a rectangle:
// Define your variables let length = 10; let width = 5; // Calculate the area let area = length * width; // Display the result console.log("Rectangle dimensions:", length, "x", width); console.log("Area:", area);
Exercise 3: String Concatenation
Concatenate your first and last name:
// Define your variables let firstName = "John"; let lastName = "Doe"; // Concatenate with a space between let fullName = firstName + " " + lastName; // Display the result console.log("First name:", firstName); console.log("Last name:", lastName); console.log("Full name:", fullName);
Exercise 4: Temperature Conversion
Convert Celsius to Fahrenheit (Formula: F = C × 9/5 + 32):
// Define temperature in Celsius let celsius = 25; // Convert to Fahrenheit let fahrenheit = celsius * 9/5 + 32; // Display the result console.log(celsius + "°C is equal to " + fahrenheit + "°F");
Guided Project: First Steps into JavaScript
Welcome to your first Guided Project video! This video will cover several essential topics related to setting up a webpage, including creating a basic HTML scaffold and adding JavaScript to your page. We will also discuss important concepts such as values, variables, and evaluating expressions in the console. Understanding these concepts will build a strong foundation for you to build on throughout this course and help you develop the skills you need to create dynamic and engaging web pages. Learning new skills can be challenging, but don't be discouraged - with practice and persistence you'll be able to master these concepts in no time!
Solution
Here is the solution to the Guided Project: