JavaScript FUNctions¶
Before we dive into functions, we need to talk a little more about JavaScript variables, because functions will often use or output variables!
Some 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
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 (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
Let’s warm up by using some variables in our init.js
file.
// original code
const map = L.map('the_map').setView([34.0709, -118.444], 5);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// adding markers
let work = L.marker([34.0709, -118.444]).addTo(map)
.bindPopup('Where I used to work on campus')
let home = L.marker([37.7409, -122.484]).addTo(map)
.bindPopup('Family in SF')
let random = L.marker([39.7409, -122.484]).addTo(map)
.bindPopup('Third Point')
Time for FUNctions¶
Programmers are often programming because they have to get something done, but a true programmer likes to automate (as well as copy and paste).
Let’s edit our init.js
and replace the marker
variable with the following:
// adding markers
let work = L.marker([34.0709, -118.444]).addTo(map)
.bindPopup('Where I work on campus')
let home = L.marker([37.7409, -122.484]).addTo(map)
.bindPopup('Family home in San Francisco')
let random = L.marker([39.7409, -122.484]).addTo(map)
.bindPopup('Third Point')
Your init.js
should look like this:
Would it be cumbersome to add 10 points like this? What about 100? 1,000?
That’s where functions come in handy!
Our first function!¶
Functions are declared like variables by a keyword, however instead of let
, const
, or var
we use the keyword… function
, so original!
A basic function looks likes this:
Let’s try to apply what this looks like with marker creation!
We know from the documentation and our previous usage that L.marker
, needs latitude
and longitude
. So, we can automate the marker creation by creating a function like this:
function addMarker(lat,lng,message){ //(1)!
console.log(message) //(2)!
L.marker([lat,lng]).addTo(map).bindPopup(message) //(3)!
return message //(4)!
}
function
is the declaration of our function,addMarker
is the name, andlat,lng,message
is the parameter, which are passed in to a function to be utilized.Parameters
are optional, but parentheses()
are not!! The{
is the begining of the function.- The
console.log
in the body will tell us if the function is working. - Here we use the
L.marker()
to add a marker - The return is used to exit a function and return a value.
Why did we include a third parameter called message
?
It allows us to customize our popups!
Notice how the how function accesses our parameters:
- L.marker
uses lat
,lng
- bindPopUp
uses message
Function parameters
You can pass in variables into functions and multiple parameters are seperated by a comma. In this function, there are 3 parameters: (lat,lng,message)
. Remember that if you even if you have NO parameters, you must include the parenthesis ()
like follows:
- js#! function our_first_function(){return "hello world"}
Go ahead and check the console!
WHAT?! Nothing has changed!
Using Functions¶
In order for a function to run, it needs to be “plugged-in”. This is called “invoking” or “calling” the function. When a function has no parameters, you can call it like so:
But since our function does have parameters (namely the lat
,lng
,and message
), you must specify what those are when you call the function.
Add this to the end of our init.js
file:
js/init.js
Warning about the order of parameters!
The order of the parameters (lat
,lng
,message
) is must be in the SAME order that the function reads them!! Try swapping the 37
and -122
to see what I mean.
Now your console should return the “message” AND you should see a new marker on the map!
Inside function
blocks you can create variables, change HTML, and do all sorts of things like play videos and even create games.
⚽Class Exercise #3 - Using the marker function¶
Create your own marker function that does the following:
- Utilizes at least
four parameters
- Declare a
new variable
inside the function Returns
a value (return
values are optional, but can be used to exit a function and return/output a value.)
Use your function to create 3 markers with it.
Check
// create function
function addMarker(lat,lng,title,message){
console.log(message)
L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2>`)
return message
}
// use the function
addMarker(37,-122,'home','home land!')
addMarker(32,-118,'work','where i work land!')
addMarker(39,-119,'location 1','random location')
addMarker(36,-120,'location 2','another random location')
If you finished early, try these extra challenges:
- Try to style your pop-up with 2 attributes!
Bonus Exercise - Create your own function
Create your own function that does the following:
- Utilizes at least
two parameters
- Declare a
new variable
inside the function Returns
a value
Bonus Answer
Combining Strings¶
We can combine strings with the +
operator. For example:
Optional shortcut: String Literals¶
We can use a backtick ` to create a string literal, which allows us to use variables inside the string.
Just be aware, that
String literals or template strings allow you to subsitute variables into strings with the ${VARIABLE_NAME}
syntax inside the place holders.
Declaring a string with ` instead of '
'
or " "
, allows you to convert variables
to strings. For example, the zoom level normally would be treated as a number, but when we brought it in with the ${}
combination it became a string so it could not be summed.
This technique will be helpful for our pop-ups as follows:
function addMarker(lat,lng,title,message){
console.log(message)
L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`) //(1)!
return message
}
- Notice how
title
is added to the<h2>
tag element andmessage
is added to an<h3>
element?
Alternative Method
You can also bundle the pop-up into a variable, and then use that to populate the bindPopup()
call: