Notes Week 3
Data type #3 - Booleans
The last primative data type that we’ll cover in this course is the Boolean type. Put simply, a boolean value is either true or false. This type essentially allows us to add logic into our programs.
We can use booleans to model concepts such as on/off, 1/0, existing/not existing, etc.
const dogsAreTheBest = true
const catsRule = false
Boolean Operators
There are a few different operators that we can use to play around with booleans.
We can use comparison operators to create a boolean value from 2 number values:
And we also have logical operators, which can combine 2 boolean values to create one boolean value:
Falsey Values
If we try to use a non-Boolean value in a Boolean context, then most values will evaluate to true. The exception is with falsey values, which JavaScript will evaluate to false.
// most values evaluate to true:
"Something" && true // => true && true => true
5 && true // => true && true => true
// these values are considered "falsey", and evaluate to false:
0 && true // => false && true => false
"" && true // => false && true => false
undefined && true // => false && true => false
null && true // => false && true => false
NaN && true // => false && true => false
Conditionals (AKA Control Flow)
We can use if statements to run code only under certain conditions:
if (condition) {
// statements to execute
}
In this case, we’ll run the code inside the curly brackets only when condition
evalues to true
.
We can also provide alternative instructions with else if and else.
const age = 20
if (age > 75) {
console.log("You are old")
}
else if (age > 18) {
console.log("You are an adult")
}
else {
console.log("You are a child/teenager")
}
Loops
We can use loops to execute blocks of code more than once.
While loops will execute a block of code continually, until the condition evaluates to false
. In this sense, you can think of them as an extension to if statements.
let bottlesOfBeer = 99
while (bottlesOfBeer > 0) {
console.log(bottlesOfBeer + " bottles of beer on the wall")
bottlesOfBeer = bottlesOfBeer - 1
}
When we use a while loop, we need to make sure that something like a counter updates on every run, or otherwise we’ll create an infinite loop, which will never end.
For Loops
Another type of loop that we can use in JavaScript is the for loop.
// initialization; conditional; iteration
for (let i = 1; i <= 10; i++) {
console.log(i)
}
For loops consist of 3 parts:
- Initialization: create a variable and assign its initial value (
let i = 1
) - Conditional: check a condition to see whether we should run the loop (
i <= 10
) - Iteration: update the value of our variable every time the code executes (
i++
)
Data structures
We can think of data structures as being like “super variables” that can store more complex data.
Last week, we learned about arrays, which are analagous to boxes.
We give these boxes a name by declaring them, and then we can put things into them by assigning values to them.
let myVar // declaration - give me a box called "myvar"
myvar = "Hello" // assignment - put "Hello" in the box
Arrays
If we want to store lots of related data in one variable, then we can put that data into an array.
Creating an array essentially gives us a row of boxes within a box. We can store a value in each of these slots.
We can put anything in each of these boxes. We declare and initialize an array like this:
let myArr // create a box called myArr to put an array in
myArr = ["Hello", "Howdy", "Hey", "Hola"] // create a 4-item array, and put it inside myArr
As long as we know the index (number - starting from zero!) that we stored each of these values in, then we can retrieve them later with the bracket notation:
let pets = ["Dog", "Cat", "Tiger"]
const bestPet = pets[0] // Dog
const boringPet = pets[1] // Cat
const dangerousPet = pets[2] // Tiger
We can also put something else into any of these mini-boxes - also using the bracket notation - or we can add more items using the push()
method.
pets[1] = "Goldfish" // ["Dog", "Goldfish", "Tiger"]
pets.push("Mouse") // ["Dog", "Goldfish", "Tiger", "Mouse"]
We can iterate through an array using the for loop. This gives us access to each item in the array, which we can do something with!
// prints the name of each pet
for (let i = 0; i < pets.length; i++) {
console.log(pets[i])
}
Objects
The last data type that we need to know about is the object. Objects are special in JavaScript - pretty much everything is an object under the hood (including arrays!). An object looks something like this:
With an object, we can essentially create many boxes inside of our variable, which can all be given a name. We can create an object like this:
let myObj // create a box + label it "myObj"
myObj = {
name: "Jolene",
smile: "Like a breath of spring",
voice: "Soft like summer rain"
} // make 3 boxes inside of myObj + put strings in them
These internal boxes (name
, smile
, voice
) are called properties. We can then use the dot notation or the bracket notation to access the value of these properties:
console.log(myObj.name) // dot notation => Jolene
console.log(myObj["smile") // bracket notation => Like a breath of spring
We can also add new boxes/properties to an object like this:
myObj.newProperty = "New value"
Function Values & Methods
So far, we’ve been writing functions like this:
function nameOfFunction() {
// code goes here
}
It turns out that there’s another way to write functions - like this:
const nameOfFunction = function() {
// code goes here
}
The function() { ... }
here is called an anonymous function, and we can treat it like a value - just like anything else! In this case, we’re storing that value in a variable called nameOfFunction, and we can then use it just like any other function:
nameOfFunction() // runs the code inside of the function
It turns out that we can also store function values as properties of our objects:
const obj = {
prop1: "Some text",
prop2: 42,
fnProp: function() {
console.log("HI!")
}
}
// we can then call our function like this
obj.fnProp() // => logs "HI!"
When we do this, these functions are called methods. We’ve actually already seen a few methods so far!
console.log()
- the log() method of the console objectArray.push()
- the push() method of the array objectdocument.write()
- the write() method of the document object