FETCH and THEN¶
Time to dive back into scary JavaScript waters! Before doing so, let
’s just make sure we are warmed-up for our swim!
Back to JavaScript variables again!¶
Need a variable refresher?
Revisiting more variable definitions¶
What we really need to understand about variables is that they act like boxes where you can store or take information out of.
- const
acts like a locked safe that will not let you put anything into it after you define it
- let
is like a regular box.
- var
is VARy
problematic because it can be both locked and unlocked
Here are some of the types in JavaScript:
//number
let box1 = 5;
let box2 = 5.0;
//string
let box3 = 'five';
let box4 = "five";
// string literal, uses backticks and ${variable} to bring in another variable
let box5 = `this is from box #4: ${box4}`;
// array, which is a list of things
let box6 = [1,2,3,4,5];
// Object, stores variables together, can be of different types!
let box7 = {"number": 'five', "value":5};
// boolean (true or false)
let box8 = true;
// null value
let emptyBox;
Remember, to declare a variable or give it a value you must use the =
symbol, like so:
Anatomy of a variable declaration
let
is the keyword declaration of a variablemy_variable
is the variable’s name"exist!"
is the value for this variable;
defines the end of a line in JavaScript
```
JavaScript Warm-up: Using Variables¶
Instead of hard coding the values, we can use variables to store the values. For example, instead of writing:
We can write:
// declare the variables
let mapCenter = [34.0709,-118.444]
const zoom = 5
// declare the map and use the variables above
const map = L.map('the_map').setView(mapCenter, zoom);
This is a little more work, but it is much easier to change the values later. For example, if we wanted to change the map center, we can just change the value of mapCenter
instead of having to change the value in multiple places.
Finished warm-up code¶
JavaScript Objects
- Boxing-up our variables¶
An object
is a unique variable that can store many other variables! Think of it as a big box where many other Lego pieces or even other boxes can be put inside!
Your object can look like this too:
Wait! Didn’t we see this somewhere?
Yep! It was in the GeoJSON we created!
The meaning behind GeoJSON
GeoJSON actually stands for “geographic” JavaScript Object Notation!
In a JavaScript object, each value has a key
and a value
.
The :
symbol seperates the key
from the value
, like this:
- Everything in an object is contained within the curly braces
{}
- Anything to left of the
:
is the key - Anything to right of the
:
is the value - New key-value pairs are separated by a comma,
,
- Warning ! Never end an object with a
,
!!!!
Accessing an object’s property¶
To access an object
’s properties we use the .
notation.
For example, myObject.key
will return the value, which in this case is.. value
!
No spaces in variable names!
You cannot use spaces in variable definitions like let my map;
, so stick with camelCase
or snake_case
when naming varibles with multiple words. When defining key
s in objects
, you can use spaces, but it is not recommended.
If you do encounter a key
with a space in it, like, let anObject = "my annoying key": "is this"
, you cannot use the .
syntax to access it you must use this alternative method:
anObject["my annoying key"]
⚽In-class Exercise #1 - Variables and console.log¶
Tasks
- Re-copy this week’s lab template with
index.html
andinit.js
- Replace the hard coded values of
const map = L.map('the_map').setView(mapCenter, zoomLevel);
with anobject
. - Get the
object
to show up in the console.
Reminder: Working with our Dev Console
In VS Code, start Live Server by clicking Go Live
.
After Firefox runs, open the Console:
- You can either right click anywhere on a page with the mouse and clicking on
Inspect
or press F12 on the keyboard.
Remember to think of the Console as the Command Line/Terminal for your browser.
Answer
Your code should look like the following:
let mapOptions = {'center': [34.0709,-118.444],'zoom':5}
const map = L.map('the_map').setView(mapOptions.center, mapOptions.zoom);
console.log(mapOptions)
-
In the console, type in
mapOptions
(or whatever you chose to name your object) then press Enter. -
You should see your JavaScript object,
mapOptions
!
Reflection
Think about the benefits of having variables in an object, is it easier to read for you? Harder?
Knowing how to check the console will help us test our JavaScript code and even run functions and methods without leaving the browser!
Finished Exercise #1 code¶
Make sure your code looks like the following before moving on:
A method to my madness?!¶
With that refresher about variables
and practice with objects
in mind, do you remember how our functions
in last week’s lab took a variable
and did something to it?
Variables have built-in functions called method
s!!!
For example, string
-type variables have methods
for changing the string, like making all the letters UPPERCASE
or splitting a character based on a . To access a method, you use the
.
after the variable has been declared as that type.
Calling methods for what they are ()
Since methods
are functions, you must call them in the same way with the ()
at the end. This is because some methods
have parameters you can fill in.
A helping console
hand!
You can check what methods are available right in Firefox’s web developer console! Most modern web browsers have this feature as well.
To give this a try, copy and paste this right into your web browser and see what happens!
let myString = "hi, this is a test string"
let divideBySpace = myString.split(" ")
console.log(divideBySpace)
Did you get this response?
result: Array(6) [ "hi,", "this", "is", "a", "test", "string" ]
If you did, yay! This is an array (list), of 6 strings!
⚽In-class Exercise #2 - What other methods are available?¶
As with all languages, learning to look-up things is important to expand what you can say and do! The following is a table of where you can find some methods:
Location | Type |
---|---|
MDN | Strings |
W3 | Strings |
W3 | Numbers |
W3 | Arrays |
W3 | Objects |
Tasks
- Visit one of the links above or search online to find other methods.
- Get the result to display in your console.
- Bonus: read the next section try to
chain
multiplemethods
together.
Answer
Here is an example of an uppercase method:
let myString = "hi, this is a test string"
let divideBySpace = myString.toUpperCase()
console.log(divideBySpace)
Result:
"HI, THIS IS A TEST STRING"
Method chaining¶
In JavaScript whenever you see a .
after a parenthesis()
,it means you are chaining a function to follow it.
For example:
let myString = "hi this is a test string"
let divideBySpace = myString.toUpperCase().split(" ")
console.log(divideBySpace)
The output should look a little bit different than last time thanks to the toUpperCase()
method!
Output
Array(6) [ "HI", "THIS", "IS", "A", "TEST", "STRING" ]
Time to fetch
and then
do something¶
To access data, we will use the JavaScript Fetch API to fetch
our GeoJSON file and then
add it to our map.
When we access the GeoJSON file with the Fetch
API we then get many methods
to use with it.
A fetch
looks like this:
fetch("map.geojson")
Wait! No variable
declaration?!
Why do you think so?
Answer
The fetch
API is actually a built-in function for JavaScript
, much like console.log()
!
Good? Let’s carry on then
!¶
fetch
actually does nothing by itself! It needs to do something with the data. Thus, fetch
is almost always used together with the then
method as follows:
fetch("map.geojson") //(1)!
.then(function aGenericDataFunctionName(data){//(2)!
return data.json()//(3)!
})
.then(function anotherGenericDataFunctionName(data){ //(4)!
// Basic Leaflet method to add GeoJSON data
L.geoJSON(data).addTo(map)//(5)!
});
map.geojson
is location of the GeoJSON file relative to our file. If you moved the file to a subdirectory calleddata
, then you would have to make thisdata/map.geojson
.- Here is our first chain, we are trying to
fetch
our geojson file. We will call ageneric
function in here. - For the next step we need a
json
, so wereturn
the value as ajson
with the.json()
method! - This is the next
then
i.e. our second chain! - This calls
L.geoJSON()
and adds ourdata
to the map.
Anoynmous functions
¶
Since our .then
is a one-time call, it does not need named functions as a part of it!
So we can make our function
anoymous by removing the name part of it.
Here’s how the simpler fetch-then
should look:
fetch("map.geojson")
.then(function (data){
return data.json()
})
.then(function (data){
// Basic Leaflet method to add GeoJSON data
L.geoJSON(data).addTo(map)
});
Looks much better, right? Well… We can shorten it even more!!!
WHAT IS THIS =>
?!!!¶
The =>
is a shortcut to define an anoynmous
function and is called an arrow-function
!
Here is how it looks in practice:
fetch("map.geojson") //(1)!
.then(response => { //(2)!
return response.json();
})
.then(data =>{ //(3)!
// Basic Leaflet method to add GeoJSON data
L.geoJSON(data).addTo(map)//(4)!
});
map.geojson
is location of the GeoJSON file relative to our file. If you moved the file to a subdirectory calleddata
, then you would have to make thisdata/map.geojson
.- Here is our first chain, we are trying to
fetch
our geojson file. - This is our next chain, we are trying to add it to our map!
- The
addTo(map)
is similar to ourmarker.addTo(map)
function call!
The map should now have a blue tint over it and you cannot interact with it. Not really useful.
Going forward we will use the arrow-function
because it is shorter, but if you want to use the other methods, feel free to.
🏁Checkpoint¶
Before moving on, check to see if JavaScript code looks like the following: