How to Use LocalStorage, SessionStorage and Cookies in JavaScript

Web storage is a powerful feature in modern browsers that allows you to store data directly on a user's computer. In JavaScript, the three primary ways to handle client-side storage are LocalStorage, SessionStorage and Cookies. In this article, we'll explore each method, explain their differences an...

? https://www.roastdev.com/post/....how-to-use-localstor

#news #tech #development

Favicon 
www.roastdev.com

How to Use LocalStorage, SessionStorage and Cookies in JavaScript

Web storage is a powerful feature in modern browsers that allows you to store data directly on a user's computer. In JavaScript, the three primary ways to handle client-side storage are LocalStorage, SessionStorage and Cookies. In this article, we'll explore each method, explain their differences and provide simple examples to get you started.


LocalStorage
LocalStorage is designed for storing data with no expiration date. This means that the data you store remains available even after the browser is closed and reopened. It’s perfect for settings, user preferences, or any other information you’d like to persist across sessions.
Key Characteristics:

Persistence: Data persists until explicitly removed.
Storage Limit: Approximately 5-10 MB per origin (depending on the browser).
Scope: Accessible only within the domain that stored it.
Basic Operations:
Setting an Item:

⛶// Save data to localStorage
localStorage.setItem('username', 'Alice');
Getting an Item:

⛶// Retrieve data from localStorage
const username = localStorage.getItem('username');
console.log(username); // Outputs: Alice
Removing an Item:

⛶// Remove a specific item
localStorage.removeItem('username');
Clearing All Items:

⛶// Remove all data from localStorage
localStorage.clear();


SessionStorage
SessionStorage is similar to LocalStorage, but with one key difference: data stored in SessionStorage is cleared when the page session ends. A page session lasts as long as the browser is open, and survives over page reloads and restores. However, once the browser is closed, the data is lost.
Key Characteristics:
Session-Based: Data is available only during the page session.
Scope: Accessible only within the tab or window where it was stored.
Usage: Ideal for temporary data, such as shopping cart contents that don’t need to persist after the session.
Basic Operations:
Setting an Item:

⛶// Save data to sessionStorage
sessionStorage.setItem('sessionData', 'This is temporary data');
Getting an Item:

⛶// Retrieve data from sessionStorage
const data = sessionStorage.getItem('sessionData');
console.log(data); // Outputs: This is temporary data
Removing an Item:

⛶// Remove a specific item
sessionStorage.removeItem('sessionData');
Clearing All Items:

⛶// Remove all data from sessionStorage
sessionStorage.clear();


Cookies
Cookies have been around much longer than the Web Storage APIs and are primarily used for storing small pieces of data that need to be sent back to the server with each HTTP request. They can have an expiration date, and you can set options like path, domain, and security flags.
Key Characteristics:
Small Data Size: Typically limited to around 4 KB per cookie.
Server Communication: Automatically sent with every HTTP request to the same domain.
Expiration: Can be set to expire at a specific time.
Basic Operations:Unlike localStorage and sessionStorage, cookies do not have a simple API for get/set operations in JavaScript. Instead, you manipulate the document.cookie string.
Setting a Cookie:

⛶// Set a cookie that expires in 7 days
const setCookie = (name, value, days) = {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
};

setCookie('user', 'Bob', 7);
Getting a Cookie:

⛶// Retrieve a cookie value by name
const getCookie = (name) = {
const cname = name + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(';');
for (let cookie of cookieArray) {
cookie = cookie.trim();
if (cookie.indexOf(cname) === 0) {
return cookie.substring(cname.length, cookie.length);
}
}
return "";
};

console.log(getCookie('user')); // Outputs: Bob
Deleting a Cookie:

⛶// To delete a cookie, set its expiry date to a past date
const deleteCookie = (name) = {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};

deleteCookie('user');


Choosing the Right Storage Option
Each storage method serves a different purpose:
LocalStorage: Best for storing data that you want to persist over long periods, such as user preferences.
SessionStorage: Ideal for data that should only be available during a single session, such as temporary form data.
Cookies: Useful when you need to send data back to the server with HTTP requests or when working with authentication tokens (keeping in mind the data size limitations).
When building your web application, consider the nature and lifetime of the data you’re storing. For example, if your application needs to remember user preferences even after closing the browser, LocalStorage is your go-to. Conversely, if you need data only during the session, SessionStorage is more appropriate.
ConclusionUnderstanding the differences between LocalStorage, SessionStorage, and Cookies is essential for effective client-side data management in JavaScript. Each method has its unique benefits and limitations:⛶_LocalStorage_ provides persistent storage across sessions.

_SessionStorage_ offers temporary storage within a single session.

_Cookies_ enable small data transfers between the client and server.By choosing the appropriate storage solution, you can optimize your web application's performance and ensure that data is handled in the most efficient manner. Experiment with these examples and see how they can enhance the user experience on your site!Happy coding!

Similar Posts

Similar

Lessons from Scaling Lead Generation Without Burning Out Your Dev Team

When your product starts gaining traction, the pressure to fill the sales pipeline grows fast.But here is the thing:
Developers are often pulled into lead qualification calls, CRM tasks, or even setting up outreach automations—and that kills productivity.After working with various growth teams, we...

? https://www.roastdev.com/post/....lessons-from-scaling

#news #tech #development

Favicon 
www.roastdev.com

Lessons from Scaling Lead Generation Without Burning Out Your Dev Team

When your product starts gaining traction, the pressure to fill the sales pipeline grows fast.But here is the thing:
Developers are often pulled into lead qualification calls, CRM tasks, or even setting up outreach automations—and that kills productivity.After working with various growth teams, we noticed a few patterns that helped ease the load:✅ Prequalify leads before they ever reach sales. No more “just exploring” calls.
✅ Prioritize quality over quantity. A handful of engaged, high-intent leads beat a list of 500 random emails.
✅ Keep your tech team out of the sales chaos. Sales ops should support devs, not rely on them.Whether you are building in public or running a SaaS with a lean team, protecting dev time is non-negotiable.https://konsyg.com/
Similar

Check out interesting insights on tracking productivity without Micromanaging


Sign in to view linked content
...

? https://www.roastdev.com/post/....check-out-interestin

#news #tech #development

Favicon 
www.roastdev.com

Check out interesting insights on tracking productivity without Micromanaging

Sign in to view linked content
Similar

Spring Architecture Series-9.Understanding Design Patterns Through Spring Framework Implementation




Introduction
Design pattern are reusable solutions to common soft ware design problems.The Spring Framework is a perfect example of how design patterns can be effectively applied to create a robust and flexible application framework. In this article,I'll explore the key design patterns used...

? https://www.roastdev.com/post/....spring-architecture-

#news #tech #development

Favicon 
www.roastdev.com

Spring Architecture Series-9.Understanding Design Patterns Through Spring Framework Implementation

Introduction
Design pattern are reusable solutions to common soft ware design problems.The Spring Framework is a perfect example of how design patterns can be effectively applied to create a robust and flexible application framework. In this article,I'll explore the key design patterns used in my miniSpring implementation.


Core Design Patterns



1. Factory Pattern
The Factory Pattern is central to Spring's IoC container:
⛶public interface BeanFactory {
Object getBean(String beanName) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name);
boolean isPrototype(String name);
Class getType(String name);
}Implementation example
⛶public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory {
protected MapString, BeanDefinition beanDefinitionMap =
new ConcurrentHashMap(256);

@Override
public Object getBean(String beanName) throws BeansException {
Object singleton = getSingleton(beanName);
if (singleton == null) {
singleton = createBean(beanName);
}
return singleton;
}
}Kay aspects:
Object creation abstraction
Dependency management
Lifecycle control



2. Proxy Pattern
The Proxy Pattern is used extensively in Spring's AOP implementation:
⛶public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
private Object target;
private PointcutAdvisor advisor;

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (this.advisor.getPointcut().getMethodMatcher()
.matches(method, target.getClass())) {
MethodInterceptor interceptor = advisor.getMethodInterceptor();
MethodInvocation invocation = new ReflectiveMethodInvocation(
proxy, target, method, args, target.getClass());
return interceptor.invoke(invocation);
}
return method.invoke(target, args);
}
}Features:
Dynamic proxy creation
Method interception
Advice application



3. Observer Pattern
The Observer Pattern is implemented in Spring's event mechanism:
⛶public interface ApplicationListenerE extends ApplicationEvent
extends EventListener {
void onApplicationEvent(E event);
}

public class SimpleApplicationEventPublisher
implements ApplicationEventPublisher {
private ListApplicationListener listeners = new ArrayList();

@Override
public void publishEvent(ApplicationEvent event) {
for (ApplicationListener listener : listeners) {
listener.onApplicationEvent(event);
}
}
}Key aspects:
Event publishing
Listener registration
Event handling



4. Template Method Pattern
The Template Method Pattern is used in JDBC operation:
⛶public class JdbcTemplate {
public Object query(String sql, Object[] args,
PreparedStatementCallBack pstmtCallBack) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = dataSource.getConnection();
pstmt = con.prepareStatement(sql);
ArgumentPreparedStatementSetter setter =
new ArgumentPreparedStatementSetter(args);
setter.setValues(pstmt);
return pstmtCallBack.doInPreparedStatement(pstmt);
} finally {
// Resource cleanup
}
}
}Features:
Algorithm skeleton
Customizable steps
Resource management



5. Strategy Pattern
The Strategy Pattern is used in various parts of Spring:
⛶public interface Pointcut {
MethodMatcher getMethodMatcher();
}

public class NameMatchMethodPointcut implements Pointcut {
private String mappedName = "";

@Override
public MethodMatcher getMethodMatcher() {
return new MethodMatcher() {
@Override
public boolean matches(Method method, Class targetClass) {
return mappedName.equals(method.getName());
}
};
}
}Key aspects:
Algorithm selection
Runtime configuration
Extensibility
## Pattern Integration
### 1. Factory and Proxy Integration

⛶public class ProxyFactoryBean implements FactoryBeanObject {
private Object target;
private PointcutAdvisor advisor;

@Override
public Object getObject() throws Exception {
return createAopProxy().getProxy();
}

protected AopProxy createAopProxy() {
return getAopProxyFactory().createAopProxy(target, this.advisor);
}
}


2. Observer and Template Method Integration
⛶public abstract class AbstractApplicationContext
implements ApplicationContext {
private ApplicationEventPublisher applicationEventPublisher;

public void refresh() throws BeansException {
// Template method steps
initApplicationEventPublisher();
registerListeners();
finishRefresh();
}

protected void finishRefresh() {
// Observer pattern usage
publishEvent(new ContextRefreshedEvent(this));
}
}


Design Pattern Benefits



1. Flexibility

Easy to extend
Loose coupling
Runtime configuration
### 2. Maintainability
Clear structure
Separation of concerns
Reusable components
### 3. Scalability
Modular design
Efficient resource management
Performance optimization



Best Practices



1. Pattern Selection

Match pattern to problem
Consider trade-offs
Avoid over-engineering
### 2. Implementation
Clean interfaces
Proper abstraction
Error handling
### 3. Integration
Pattern combination
Resource management
Performance consideration



Common Challenges and Solutions

Complexity Management


Clear hierarchy
Interface segregation
Documentation


Performance


Caching strategies
Resource pooling
Lazy initialization


Extensibility


Extension points
Plugin architecture
Custom implementations





Conclusion
Understanding design patterns through Spring implementation provides:
Deep insight into pattern usage
Practical application examples
Best practice guidelines
Problem-solving strategies
Key takeaways:
Pattern selection criteria
Implementation techniques
Integration approaches
Performance considerations
This implementation demonstrates how design patterns can be effectively combined to create a robust and flexible framework.