Skip to content

if Conditional Statements in JavaScript

Conditional statements are important for being able to tell our code to do or not do something.

Evaluting an if condition

if(){
    // do something if this is true
}
  1. if statments begin with the if keyword.
  2. The () contains the evaluating condition.
  3. The {} contains the function to do if the statement is true.

The syntax is similar to a function in that they both have parameters and open and close with brackets {}.

const hello = "hi"
if (hello){
    // do something if the `hello` variable exists
    console.log('this condition is true!')
    // optional: return something
} 

Defined vs. undefined variables

Variables that do no have a = afterwards, means they have no value and are called undefined:

let goodbye

Undefined variables can also be created with the following variable definitions:

let goodbye = null
let goodbye = 0

// are all the same as
// let goodbye

Negating conditions

You can also negate a condition by adding a ! in front, for example:

const hello = "hi"
let goodbye

if (!hello){
    // do something if the `hello` variable is undefined
    // optional: return something
    console.log('in a conditional!')
} 

This statement wouldn’t work since hello is defined, but if we change the if evaluation variable insde the () to goodbye, it will evalue as true since goodbye is undefined:

const hello = "hi"
let goodbye

if (!goodbye){
    // do something if the `hello` variable is undefined
    // optional: return something
    console.log('this condition is true!')
} 

JavaScript Conditional Evaluation Types

Recall that the if keyword that evalutes the condition within the (), like the parameters in a JavaScript function.

There are different ways to set conditions inside the (), but it must has to either be true or false.

Here are some different types of evaluations:

Example Meaning
if(variable) Does this variable exist?
if(variable == "yes") Does this variable equal to “yes”
if(variable != "yEs") Does this variable NOT equal “yEs”
if(variable > 10 ) Is this variable greater than 10?
if(variable == false) Is this variable false?
if(variable == null) Is this variable null?
if(variable == anotherVariable) Is this variable the same as another variable?
if(variable > 1 && variable < 10) Is this variable greater than 1 AND is variable less than 10?

You can check this MDN article on truthy and falsy for more examples:

The && is a logical AND operator where all statements have to be True in order to be statisfied.

const hello = "hello"
const goodbye
if (hello && goodbye){
    console.log('I dont know why you say goodbye, I say hello')
}

Great, what else is there?

else acts like a default in case the if condition never is true:

const hello = "hello"
const goodbye
if (hello && goodbye){
    // do something IF `hello` and `goodbye` exist 
    console.log('I dont know why you say goodbye, I say hello')
}
else {
    // do something else
    console.log('you say goodbye, and i say hello')
}

⚽Class Exercise #1: Let’s see IF you get the idea!

Tasks

  1. Create an if-else statement for the dataset in your mapplication within the addMarker() function to only add markers when a certain condition exists

If you are using the lab dataset, filter out answers to the question"Have you been vaccinated?"

Reminder!

The key you are using to access the object MUST match identically to the Google Sheet!!! But, you can CHANGE the Google Sheet if you want your keys to be easier to

function addMarker(data){
    L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>${data.timestamp}</h2>`)
    createButtons(data.lat,data.lng,data['What zip code do you live in?'])
    return data
}

Bonus

Use an else statement to show the number of those who speak other languages. Hint: You can add variables by using the syntax anyVariable += 1

Answer
js/init.js
function addMarker(data){
    if(data['Have you been vaccinated'] == "Yes"){
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
    }
    else{
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Not vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
        // Bonus:    
        // notVaccinated += 1
    }
    return data
}
// let notVaccinated = 0
function processData(results){
    console.log(results)
    results.data.forEach(data => {
        console.log(data)
        addMarker(data)
    })
    //document.body.append("Number of hidden records:"+notVaccinated)
}
js/init.js
function addMarker(data){ //(1)!
    if(data['Have you been vaccinated?'] == "Yes"){ //(2)!
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
    }
    else{
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Non-Vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
    }
    return data
} 
  1. The best place to change is the addMarker() function, since the function is already looping through all of our data (as per the previous lab).

  2. Put an if(){} statement right at the start of function to indicate that the first thing that should happen is evaluating this function.

  3. Then choose the variable to evaluate, which will be a field from our data object called, Have you been vaccinated. Remember, the field MUST match exactly how it is written in the CSV data set!

  4. Next we use the == to evaluate the condition as equals to

  5. Then we set the evaluation value, in this case “Yes”. The quotes is necessary because without it, it treats Yes as a variable called Yes!!

  6. We change the pop-up to reflect the True nature of our question.

  7. We then add an else{} after the closing } of the if statement.

  8. We change the pop-up to reflect the False nature of our question.

What happened to the pop-ups in the solution above?

They changed depending on whether “Yes” was evaluated or not because of our bindPopUp() change.

Before moving on, make sure your JavaScript is similar to the following:

🏁Check point

js/init.js
// declare variables
let mapOptions = {'center': [34.0709,-118.444],'zoom':5}

// define the leaflet map
const map = L.map('the_map').setView(mapOptions.center, mapOptions.zoom);

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);

function addMarker(data){
    if(data['Have you been vaccinated?'] == "Yes"){
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
    }
    else{
        L.marker([data.lat,data.lng]).addTo(map).bindPopup(`<h2>Not vaccinated</h2>`)
        createButtons(data.lat,data.lng,data.Location)
    }
    return data
}

function createButtons(lat,lng,title){
    const newButton = document.createElement("button"); // adds a new button
    newButton.id = "button"+title; // gives the button a unique id
    newButton.innerHTML = title; // gives the button a title
    newButton.setAttribute("lat",lat); // sets the latitude 
    newButton.setAttribute("lng",lng); // sets the longitude 
    newButton.addEventListener('click', function(){
        map.flyTo([lat,lng]); //this is the flyTo from Leaflet
    })
    const spaceForButtons = document.getElementById('placeForButtons')
    spaceForButtons.appendChild(newButton);//this adds the button to our page.
}

const dataUrl = "https://docs.google.com/spreadsheets/d/e/2PACX-1vSNq8_prhrSwK3CnY2pPptqMyGvc23Ckc5MCuGMMKljW-dDy6yq6j7XAT4m6GG69CISbD6kfBF0-ypS/pub?output=csv"

function loadData(url){
    Papa.parse(url, {
        header: true,
        download: true,
        complete: results => processData(results)
    })
}

function processData(results){
    console.log(results)
    results.data.forEach(data => {
        console.log(data)
        addMarker(data)
    })
}

loadData(dataUrl)