Javascript Hand Out
Javascript Hand Out
Javascript Hand Out
2)
Disclaimer
This lab assumes prior knowledge in basic HTML.
Lab Setup
The presentation slides can be found h
ere.
The only software that you’ll need for this lab is Google Chrome and a text
editing tool s uch as Sublime, Atom, VSCode, etc.
What is JavaScript?
JavaScript is an object-oriented scripting language used on the client side of
web browsers. JavaScript helps to make webpage content dynamic and
interactive, leading to the creation of friendlier interfaces for users.
You will use this console to write JavaScript code that will directly modify and
interact with this web page. You will type your code into the console, then
press Enter to run it. To try this out, enter the following code into Chrome’s
console:
1
console.log("Hello World!");
This will print out the line “Hello World!” directly beneath the code you just
ran.
console.log() is the JavaScript command for printing statements, and is
equivalent to System.out.println() in Java.
Note that beneath the "Hello World!" line there is one other line that gets
printed: a light grey line stating "undefined". After executing your print
statement, Chrome attempts to return some sort of value for your program.
The “undefined” keyword signals that nothing has been returned; it is the
JavaScript equivalent of null.
Variables
JavaScript stores data in variables. You can declare variables in JavaScript
using the keywords “const” and “let”. You should use “const” when the
variable’s value will never be reassigned, and “let” when the variable’s
value might be reassigned. N ote that “let” does not only indicate that the
variable's value may change, but also that the variable will only be used in the
block that it's defined in. This means that a variable declared with “let” may
not always be accessible by the entirety of your code. It’s standard practice to
use “const” to declare variables whenever applicable. We recommend you
use “const” as often as your own code allows.
Note that JavaScript doesn't care what type of data the variable is, and you
therefore do not need to explicitly declare a variable's type when declaring
the variable. JavaScript will automatically detect a variable’s type depending
on the value associated with that variable. You can check this by running
"typeof [VARIABLE NAME];" into Chrome’s console.
In order to get comfortable using and declaring variables, we’re going to run
a couple of tests within Chrome’s console. Run the following lines:
2
const milk = "Almond";
const sweetened = false;
let quantity = 50;
These variables are saved locally within the console. To test this, try running
console.log(milk);
The printed line should display "Almond". Now try running the following
code:
milk = "Coconut”;
quantity += 25;
console.log(quantity);
The console should not return an error, as we declared quantity with “let”.
Instead, the console should return a value of 75.
In addition to the primitive data types we’ve been declaring thus far,
JavaScript also has variable objects. Objects are variables that contain
information in the form of key-value pairs. JavaScript objects are very
similar to hashmaps, except they’re able to store variables of different data
types.
const almondMilk = {
name: "Almond",
sweetened: false,
quantity: 50
};
This creates an object called milk. You can directly change the values in this
object by running the following lines of code:
3
almondMilk.quantity += 25;
almondMilk.sweetened = true;
console.log(almondMilk.quantity);
console.log(almondMilk.sweetened);
Note that although we declared almondMilk with “const”, we were still able to
change the values contained within player. In this case, cereal itself is the
variable that we cannot reassign to a new object.
As a final note on variables, it’s important to know that that y ou should use
"===" as opposed to "==" in order to compare two variables in JavaScript.
"==" implicitly casts the variables being compared to the same type, while
"===" does not. “===” will evaluate to false if the inputs are of different types.
Functions
Functions in JavaScript are essentially objects. You declare them like this:
function pourCereal(cerealName) {
console.log(cerealName + “ has been poured!”);
};
4
ES6 Syntax
JavaScript ES6 introduced new syntax which makes function declarations
simpler. Here is an example of the pourCereal function written with ES6:
Fun tip: E
S6 also introduced template literals! These allow you to use
variables inside of a string instead of having to use + to concatenate them, as
shown above. The pourCereal function could further be simplified to:
Familiarizing yourself with ES6 will help you learn React later in the semester!
Classes
JavaScript provides clear and simple syntax for declaring classes and using
inheritance. They are designed to be easy to use, and are useful in
approaching JavaScript from a more object-oriented perspective.
To declare a class, use the “class” keyword with the desired name of the class.
In this example, we will create a class named “Student”.
class Student {
constructor(name, year, favoriteCereal) {
this.name = name;
this.year = year;
this.favoriteCereal = favoriteCereal;
this.id = “13877865”;
}
}
5
You can create new instances of the Student class by running the below
code:
Learning about JavaScript classes and their associated syntax will help greatly
when we start the Development assignment later on in the semester, as
JavaScript classes are very closely related to certain aspects of React, the
JavaScript library that we will be using in Development.
Stencil Code
Please download the s tencil code repo and unzip the folder.
Exercise I
To get more practice with JavaScript, we’re going to be making a webpage
that displays a cereal box and name on the click of a button.
HELPFUL TIPS:
1) You can get an html element on the page with
document.getElementById(<id of that element>). For example, if
an h2 element on the page has the id “myId”, then you can get that
html element by using document.getElementById(“myId”).
2) You can set the contents of an html element y ou got (see tip 1), by
accessing the ‘innerHTML’ property of that element. For example, once
we grab an h2 element on the page with id “myId”, we can set it’s
contents:
6
document.getElementById(“myId”).innerHTML = “new content”
3) You can set the src of an img (ie. the path to the image file), by
accessing the ‘src’ property of an img element. For example, if we have
an img element with id “myImg”, we can set it’s src file using:
document.getElementById(“myImg”).src = “pathToImg.src”
CHECK OFF:
Call over a TA and show the page in action. You should show:
1) The page before the button is pressed (you can just refresh the page).
An empty shelf should be shown.
2) When the button is pressed, an image of Frosted Flakes should be
displayed, and the text “Frosted Flakes” should be shown above the
image.
3) Place a breakpoint in some function of the file using Chrome Developer
Tools and demonstrate how that breakpoint gets hit by interacting
with the webpage.
Exercise 2
Now that you’ve mastered the basics, you’re going to use your new skills to
create a website that generates a random cereal when the button is pressed
and keeps a tally of how many times each cereal was generated.
EXERCISE:
1) Now you’ll be working with cereal2.html a nd cereal2.js. Follow the
TODOs in cereal2.js to generate a random cereal when the button is
pressed, and update the tally board to record how often each cereal is
suggested.
HELPFUL TIPS:
1) Syntax for writing conditional statements is linked here. This s ite has a
lot of good tutorials for javascript concepts.
2) Remember how to create classes! Reference the ‘Classes’ section of this
document if you need help.
3) Check this resource for how to access an element in a list/array.
4) Remember how to access fields of an instance of a class!
5) The tips from Exercise 1 still apply!
7
CHECKOFF:
Call over a TA and show them:
1) The page before the button is pressed (where an empty shelf is
shown).
2) Clicking the button should show a cereal box, display the name of
the cereal, and increment the corresponding counter on the left.
3) ES6 syntax for the changeCereal() function.
EXERCISE:
1) Re-implement your incrementCerealCount() function so that it maps
the current count of each cereal to the text of the corresponding t
d
element. This solution should not require an if statement. T he
function body for i ncrementCerealCount() does not need to be
longer than two lines of code.
HELPFUL HINTS:
1) You’re going to need to update the t
d element of a C
ereal without
knowing whether it’s Frosted Flakes, Captain Crunch, or Lucky Charms.
Think about how you can augment the Cereal class to do this!
CHECKOFF:
Call over a TA and show them:
1) The tally working as in Exercise 2.
2) Your incrementCerealCount() function.
Feel free to call over the TAs if you are stuck or have any questions!