Day 16 of learning JavaScript: truthy & falsy

Sven WillhaukSven Willhauk
2 min read

Hello, today we will fix a problem in the Chrome extension. The stored leads aren't getting displayed when we refresh the page. So how we want the extension to work is: If the local storage is empty, nothing will happen. If the local storage contains something, the renderLeads() function should be called so that the content gets displayed.

That's where I learned about truthy and falsy.

Falsy: false, 0, " ", null, undefined, NaN

Truthy: every other statement

When the local storage is empty, it's defined as null. That means that it is false. We need this info so that we can fix the problem more easily. We can just check if the local storage is truthy. and if so, setting myLeads to its value and call the renderLeads() function.

let myLeads = []
const inputEl = document.getElementById("input-el") 
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")

// storing the leads from local storage in an array
let leadsFromLocalStorage = JSON.parse( localStorage.getItem("myLeads"))

// if the variable is truthy, execute the if statement
// otherwise if it's null, do nothing
if (leadsFromLocalStorage) {
    myLeads = leadsFromLocalStorage // filling the myLeads array with the leads from local storage
    renderLeads() // render keads
}

inputBtn.addEventListener("click", function(){
    myLeads.push(inputEl.value)
    inputEl.value = ""
    localStorage.setItem("myLeads", JSON.stringify(myLeads))
    renderLeads()
})



function renderLeads(){
    let listItems = ""

    for(let i = 0; i < myLeads.length; i++){
        listItems += `
            <li>
                <a href= '${myLeads[i]}' target='_blank'>
                    ${myLeads[i]}
                </a>
            </li>`
    }

    ulEl.innerHTML = listItems
}

If there's now content in the local storage and we refresh the page, the leads are still displayed. And if there's nothing in the local storage, nothing happens.

Hopefully, you learned something valuable!

0
Subscribe to my newsletter

Read articles from Sven Willhauk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sven Willhauk
Sven Willhauk

I'm a 15 year old, who's on his journey to becoming a very good programmer. In the moment I can program in C#, HTML and CSS and I am learning JavaScript right now.