Skip to content

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:

let my_variable = "exist!";

Anatomy of a variable declaration

  • let is the keyword declaration of a variable
  • my_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.

js/init.js
// 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: '&copy; <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:

js/init.js
// 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:

js/init.js
// 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: '&copy; <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 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')

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:

function our_first_function(){
    console.log('hello from our first function')
}

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:

js/init.js
function addMarker(lat,lng,message){ //(1)!
    console.log(message) //(2)!
    L.marker([lat,lng]).addTo(map).bindPopup(message) //(3)!
    return message //(4)!
}
  1. function is the declaration of our function, addMarker is the name, and lat,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.
  2. The console.log in the body will tell us if the function is working.
  3. Here we use the L.marker() to add a marker
  4. 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:

    function_name()

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

    addMaker(37,-122,'you are awesome! you automated a marker function')

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
    // create function
    function addNumbers(value1,value2){
        let result = value1 + value2
        return result
    }

    // use the function
    addNumbers(1,10)   // result: 11

Combining Strings

We can combine strings with the + operator. For example:

let zoomLevel = 10
let popup = 'The zoom level is ' + zoomLevel

Optional shortcut: String Literals

We can use a backtick ` to create a string literal, which allows us to use variables inside the string.

let zoomLevel = 10
let popup = `The zoom level is ${zoomLevel}`

Just be aware, that

let popup = `${zoomLevel} + ${zoomLevel}`

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
}
  1. Notice how title is added to the <h2> tag element and message 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:

let popup_message = `<h2>${title}</h2> <h3>${message}</h3>`
L.marker([lat,lng]).addTo(map).bindPopup(popup_message)

🏁Final Checkpoint

js/init.js
// declare map variable
const map = L.map('the_map').setView([34.0709,-118.444], 5);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// create a function to add markers
function addMarker(lat,lng,title,message){
    console.log(message)
    L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`)
    return message
}

// use our marker functions
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')
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Basic Leaflet Map</title>
        <meta charset="utf-8" />
        <link rel="shortcut icon" href="#">
        <link rel="stylesheet" href="styles/style.css">

        <!-- Leaflet's css-->
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />

        <!-- Leaflet's JavaScript-->
        <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    </head>

    <body>
        <div class="main">
            <div id="contents">
                <!-- hint: the majority of lab 1 assignment can go here -->
            </div>
            <div id="the_map"></div>
        </div>
    </body>
    <script src="js/init.js"></script>
</html>