DEV Community

[Comment from a deleted post]
Collapse
 
alephnaught2tog profile image
Max Cerrina
  • Why we care: the Web is stateless. If I go into the console right now and do document.getElementById("page-content").style.backgroundColor = "orchid";, the background turns orchid! If you refresh the page, that disappears. Which I won't do, because if I do, I'll lose this content, too. Noticeably, most sites have log-ins or a means of "remembering" information: that data has to persist somewhere. For complex things like user logins, the site is (probably(3)) using a database to store that info somewhere; but not everything needs, or has access to, a database. Cookies and session variables and things like sessionStorage and localStorage allow you to persist data for a site--so that if I say I want the background here to ALWAYS be orchid, that's fine, but that data needs to get saved somewhere and then fetched for use.

Imagine playing a game: if every time you stopped playing the game and then came back later, it'd be no fun if you had to start over every single time, right? You'd have to go back to Level 1 every time you opened the game and you couldn't finish--unless the game was short or you played without interruption for a very long time.

Being able to persist data and information is massively awesome and a legit game-changer. (I feel like, along with IO, it's one of those tiers where when you learn how to do it in a given language a million new doors and rabbitholes open up because of how exponentially what you can do increases.)

sessionStorage and localStorage are really pretty friendly in Javascript. I havne't done huge amounts with them, but it's key-value pairs.

  • Session = until you close that tab(1). In Javascript(2), you can add items to sessionStorage by using the setItem method and a key-value pair:
// add an item to it
sessionStorage.setItem("firstSessionKey", "firstSessionValue");

// to retrieve that item
const bucketForValue = sessionStorage.getItem("firstSessionKey");
  • Cookies I admit I'm not familiar with from the Javascript end, but as I've learned in PHP (and I am assuming cookies are cookies in this case, even if implementation differs, someone please correct me!) cookies are a means of storing that info but on the user's computer. Hence the ability to clear cookies etc. in most (all? I hope?) browsers. You can find them on your computer itself. (Also why they are a security risk!) Cookie implementation in Javascript I will leave to W3: w3schools.com/js/js_cookies.asp

(1) Closing the tab and opening that page again in another tab ends the session; if you close the tab and reopen it, so say you close it then on FF you ctrl-shift-T and reopen it, the session is restored.

(2) Sessions in PHP, at least, are different if similar. In PHP, the data is stored on the server--there is a dichotomy-ish between cookies and sessions in that regard, storing client-side vs. server-side. Assuming no database is involved, my understanding of sessions in Javascript is that they are also client-side stored because, well, Javascript. (And assuming no AJAX, etc.)

(3) I hesitate to ever use absolutes :P

Collapse
 
alephnaught2tog profile image
Max Cerrina • Edited

Quick sloppy demo (HTML etc included for demo purposes)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Session Demo</title>
</head>
<body>
    <p>
        When this page first loads, the first time you open it before clicking
        any buttons--the background is white.
    </p>
    <p>
        When you click red or green, then refresh the page, the color changes
        to that. If you close the tab entirely and open a new
        tab and open the url again--white again.
    </p>
    <p>
        If you hit the yellow button and refresh, it's yellow. If you close
        the tab like before, do a new one, open the page again--yellow!
    </p>
    <p>If you do yellow then green or red, and refresh, green or red
       wins--until you close that tab and reopen it, even close the browser
       and reopen it, and then it will be yellow... because you picked
       yellow!</p>
    <button onclick="pickRed()"
            style="background-color: red; color: white;">Red!
    </button>
    <button onclick="pickGreen()"
            style="background-color: green; color: white;">Green!
    </button>
    <button onclick="setLocalStorageToYellow()"
            style="background-color: yellow;">Set localstorage to yellow
    </button>
    <script>
        if (sessionStorage.getItem("chosenBackgroundColor") !== null)
        {
            document.body.style.backgroundColor =
                    sessionStorage.getItem("chosenBackgroundColor");
        }
        else if (localStorage.getItem("localBackgroundColor") !== null)
        {
            document.body.style.backgroundColor =
                    localStorage.getItem("localBackgroundColor");
        }


        // functions!
        function pickRed()
        {
            sessionStorage.setItem("chosenBackgroundColor", "red");
        }

        function pickGreen()
        {
            sessionStorage.setItem("chosenBackgroundColor", "green");
        }

        function setLocalStorageToYellow()
        {
            localStorage.setItem("localBackgroundColor", "yellow");
        }
    </script>
</body>
</html>
Collapse
 
johndoesup profile image
abhishek

😻 thanks, M. Shemayev for your wonderful explanation.