Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

JavaScript Local Storage, Session Storage, and Cookies – Storing Data in the Browser

Modern websites do much more than simply display information. They remember user preferences, maintain login sessions, store shopping cart items, and save application settings.

For example:

  • Remembering a user's dark mode preference

  • Keeping products in a shopping cart

  • Maintaining login sessions

  • Saving language settings

  • Tracking website visits

To achieve this, browsers provide storage mechanisms such as:

  • Local Storage

  • Session Storage

  • Cookies

These technologies allow websites to store data directly inside the user's browser.

In this article, we will learn:

  • What browser storage is

  • Local Storage

  • Session Storage

  • Cookies

  • Differences between them

  • Practical examples

  • Real-world applications


What is Browser Storage?

Browser storage allows websites to save data directly in the user's browser.

Without browser storage:

Refresh Page
    ↓
Data Lost

With browser storage:

Refresh Page
    ↓
Data Remains Available

This improves user experience and reduces server requests.


Why Browser Storage is Needed

Imagine an online shopping website.

Without storage:

Add Product to Cart
      ↓
Refresh Page
      ↓
Cart Becomes Empty

This would frustrate users.

With storage:

Add Product to Cart
      ↓
Refresh Page
      ↓
Cart Still Available

This creates a much better experience.


Types of Browser Storage

JavaScript provides three main storage mechanisms:

Storage TypePurpose
Local StoragePermanent browser storage
Session StorageTemporary session storage
CookiesSmall data sent to server

What is Local Storage?

Local Storage stores data permanently in the browser.

Data remains available even after:

  • Refreshing the page

  • Closing the browser

  • Restarting the computer

The data remains until it is manually removed.


Local Storage Characteristics

  • Stores data permanently

  • Larger storage capacity

  • Client-side storage

  • Easy to use


Storing Data in Local Storage

Syntax:

localStorage.setItem(key, value);

Example:

localStorage.setItem("name", "Rahul");

The value is stored in the browser.


Retrieving Data

Syntax:

localStorage.getItem(key);

Example:

let name = localStorage.getItem("name");

console.log(name);

Output:

Rahul

Updating Data

Example:

localStorage.setItem("name", "Amit");

The previous value is replaced.


Removing Data

Syntax:

localStorage.removeItem(key);

Example:

localStorage.removeItem("name");

The stored value is deleted.


Clearing All Local Storage

Syntax:

localStorage.clear();

Example:

localStorage.clear();

All stored data is removed.


Storing Numbers

Local Storage stores everything as strings.

Example:

localStorage.setItem("age", 20);

Actually stored as:

"20"

Storing Objects

Objects must be converted into JSON before storing.

Example:

let student =
{
    name:"Rahul",
    age:20
};

localStorage.setItem(
"student",
JSON.stringify(student)
);

Retrieving Objects

let data =
localStorage.getItem("student");

let student =
JSON.parse(data);

console.log(student.name);

Output:

Rahul

What is Session Storage?

Session Storage is similar to Local Storage.

The main difference is:

Data exists only during the current browser session.

When the browser tab is closed:

Data is automatically deleted.

Session Storage Characteristics

  • Temporary storage

  • Faster access

  • Tab-specific

  • Automatically cleared


Storing Data

sessionStorage.setItem(
"name",
"Rahul"
);

Retrieving Data

let name =
sessionStorage.getItem("name");

console.log(name);

Output:

Rahul

Removing Data

sessionStorage.removeItem("name");

Clearing Session Storage

sessionStorage.clear();

Session Storage Example

sessionStorage.setItem(
"loggedIn",
"true"
);

The user remains logged in while the tab is open.

Once the tab closes:

Session Ends
     ↓
Data Removed

Local Storage vs Session Storage

FeatureLocal StorageSession Storage
Capacity5–10 MB~5 MB
PersistencePermanentTemporary
Browser RestartData RemainsData Removed
Tab ClosingData RemainsData Removed
Use CaseUser PreferencesLogin Sessions

What are Cookies?

Cookies are small pieces of data stored in the browser.

Unlike Local Storage:

Cookies are automatically sent to the server with every request.

Real-Life Example

When a user logs into a website:

Server
   ↓
Creates Cookie
   ↓
Browser Stores Cookie
   ↓
Future Requests Include Cookie

This helps the website recognize the user.


Cookie Structure

Name=Value

Example:

username=Rahul

Creating a Cookie

document.cookie =
"username=Rahul";

Reading Cookies

console.log(document.cookie);

Output:

username=Rahul

Creating Multiple Cookies

document.cookie =
"name=Rahul";

document.cookie =
"city=Kolkata";

Output:

name=Rahul; city=Kolkata

Setting Cookie Expiration

document.cookie =
"username=Rahul;
expires=Fri, 31 Dec 2027 12:00:00 UTC";

The cookie remains valid until the specified date.


Session Cookie

document.cookie =
"user=Rahul";

Without an expiration date, the cookie is deleted when the browser closes.


Deleting Cookies

document.cookie =
"username=;
expires=Thu, 01 Jan 1970 00:00:00 UTC";

The cookie is removed.


Cookie Attributes

AttributePurpose
expiresExpiration date
max-ageLifetime
pathURL path
secureHTTPS only
SameSiteSecurity control

Local Storage vs Cookies

FeatureLocal StorageCookies
Capacity5–10 MB~4 KB
Sent to ServerNoYes
SpeedFasterSlower
Storage SizeLargeSmall
SecurityModerateBetter with HTTPOnly

Practical Project – Dark Mode Preference

HTML:

<button onclick="enableDarkMode()">
Dark Mode
</button>

JavaScript:

function enableDarkMode()
{
    document.body.style.background =
    "black";

    document.body.style.color =
    "white";

    localStorage.setItem(
    "theme",
    "dark"
    );
}

Loading Saved Theme

window.onload =
function()
{
    let theme =
    localStorage.getItem(
    "theme"
    );

    if(theme=="dark")
    {
        document.body.style.background =
        "black";

        document.body.style.color =
        "white";
    }
};

The theme remains active even after refreshing the page.


Practical Project – Visit Counter

let count =
localStorage.getItem("visits");

if(count==null)
{
    count = 1;
}
else
{
    count++;
}

localStorage.setItem(
"visits",
count
);

console.log(
"Visits: " + count
);

Output:

Visits: 1
Visits: 2
Visits: 3

Best Practices

  • Use Local Storage for user preferences.

  • Use Session Storage for temporary session data.

  • Use Cookies for authentication tracking.

  • Convert objects using JSON.stringify().

  • Retrieve objects using JSON.parse().

  • Never store passwords or sensitive information in Local Storage.


Real-World Applications

Browser storage is used in:

  • Dark Mode Settings

  • Shopping Carts

  • User Preferences

  • Remember Me Login

  • Language Selection

  • Analytics Tracking

  • Session Management

Modern websites rely heavily on browser storage to provide a smooth user experience.


Conclusion

Local Storage, Session Storage, and Cookies are essential tools for modern web development. They allow websites to remember information, improve performance, and provide a personalized experience.

Understanding when to use each storage mechanism is an important skill for every JavaScript developer.

Local Storage is ideal for permanent data, Session Storage is suitable for temporary sessions, and Cookies are useful when data needs to be shared with the server.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? ๐Ÿ“Œ Readability – Comments make code easier to understand for you and others. ๐Ÿ“Œ Maintenance – When you revisit your code after months, comments remind you what you were doing. ๐Ÿ“Œ Collaboration – In team projects, comments explain code to fellow developers. ๐Ÿ“Œ Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . ๐Ÿ’ป Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } ๐Ÿง  Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

๐Ÿ’ก Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. ๐Ÿง‘‍๐Ÿ’ป Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...