🚀 Browser Storage in JavaScript — Simple to Use, Tricky to Explain in Interviews Saving data in the browser is easy… Explaining when and why to use each option in interviews? That’s where many developers struggle. Let’s make it crystal clear 👇 🔹 1️⃣ sessionStorage • Data is stored per tab/session • Automatically cleared when the tab closes • Not shared across tabs • Size limit ≈ 5MB ✔️ Best for: Temporary data like form steps, session-specific state 🔹 2️⃣ localStorage • Data persists even after browser restart • Shared across tabs (same origin) • Size limit ≈ 5–10MB • Synchronous API ✔️ Best for: User preferences, theme settings, small cached data 🔹 3️⃣ Cookies • Automatically sent with every HTTP request • Very small size (~4KB) • Can have expiry time • Supports HttpOnly & Secure flags ✔️ Best for: Authentication (especially secure tokens via HttpOnly cookies) 🔹 4️⃣ IndexedDB • Stores large, structured data • Asynchronous API (non-blocking) • Supports objects, files, blobs • Much higher storage limits ✔️ Best for: Offline apps, large datasets, complex client-side storage 🎯 Interview-Ready Summary 👉 sessionStorage → per tab, temporary 👉 localStorage → persistent, shared 👉 Cookies → small, sent with requests 👉 IndexedDB → large, structured, async 💡 Key Insight Choosing the right storage is not about syntax… It’s about security, performance, and use-case clarity. That’s exactly what interviewers are looking for. 💬 Which one do you use most in real projects — localStorage or cookies? #JavaScript #FrontendDevelopment #WebDevelopment #BrowserStorage #ReactJS #CodingInterview #FrontendEngineer #WebPerformance 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content.
Browser Storage Options in JavaScript Explained
More Relevant Posts
-
Here’s something commonly asked in JavaScript interviews 👇 Shallow vs Deep Copy Shallow Copy Copies only top-level properties. Nested objects are copied by reference, so changes affect the original. 👉 Ways: Object.assign(), spread (...), Array.from() Deep Copy Creates a fully independent copy, including nested objects. A common approach: JSON.parse(JSON.stringify(obj)) ⚠️ Catch with JSON.stringify() It fails for: • functions (removed) • undefined (removed or become null if arr) • Date (becomes string) • NaN / Infinity (become null) • Map, Set, RegExp (structure lost) • circular references (error) ✅ Better approach const newObj = structuredClone(obj) ✔ Handles most cases (Map, Set, Date, circular refs) ❌ Still can’t clone functions 🔥 Advanced: Custom Deep Clone If you also want to handle functions, you need a custom solution: function deepClone(obj) { if (obj === null || typeof obj !== "object") return obj; if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj === "function") return obj.bind({}); if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } const cloned = {}; for (let key in obj) { cloned[key] = deepClone(obj[key]); } return cloned; } ⚠️ Note: • Functions are copied by reference (true cloning isn’t really possible) 💡 Takeaway • Use shallow copy for simple cases • Use structuredClone() for most real scenarios • Use custom clone only when you need full control Don't forget to follow Mohit Sharma 🚀 for more. #JavaScript #Frontend #WebDevelopment #InterviewPrep #ReactJS
To view or add a comment, sign in
-
I built a free interview prep reference for JavaScript, Next.js & RTK Query — with the help of Claude AI. 🚀 🔗 Live site: https://lnkd.in/d5QP-usa I used Claude to organize, structure, and expand every concept into a clean, searchable reference site. What would've taken days took hours. 🟡 JavaScript → Closures, Event Loop, Promises, Generators → Debounce/Throttle, Currying, Proxy, WeakMap → Hoisting, Prototype Chain, Immutability 🟣 React & Next.js → Server vs Client Components → App Router, Server Actions, Middleware → All 4 caching layers explained → ISR, Streaming, generateStaticParams → All major hooks with real patterns 🟢 RTK Query → useQuery, useMutation, cache tags → Optimistic updates, token refresh → Dependent queries, prefetching → onCacheEntryAdded & lazy queries 32 interview Q&As with full answers + code examples. All in one clean, searchable reference. Built with Claude. This is the future of building dev tools — AI as a thought partner, not just a code generator. Save this for your next interview prep session 🔖 #JavaScript #NextJS #Redux #ReactJS #WebDevelopment #FrontendDeveloper #CodingInterview #Claude #AI #TechCareers
To view or add a comment, sign in
-
JavaScript Hoisting: The Interview Question That Tricks Everyone 🚀 Most developers think they know hoisting. Then the interviewer shows them tricky code. Here's your complete guide to mastering it. --- 🎯 The Definition Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. Key rule: Only declarations are hoisted, NOT initializations. --- 📊 The 3 Types (With Examples) 1. var – Hoisted & Initialized as undefined ```javascript console.log(name); // undefined (not error!) var name = "John"; // JS reads it as: // var name; → console.log(name); → name = "John"; ``` 2. let/const – Hoisted but NOT Initialized (TDZ) ```javascript console.log(age); // ❌ ReferenceError let age = 25; // Temporal Dead Zone – exists but inaccessible ``` 3. Function Declarations – Fully Hoisted ```javascript greet(); // ✅ "Hello" – works! function greet() { console.log("Hello"); } // Function expressions? NOT hoisted! ``` --- 🌍 Real-World Example The Bug That Wastes Hours: ```javascript function processOrders(orders) { for (var i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // undefined × 3 }, 1000); } } // Why? var is function-scoped, hoisted to top. // Fix: Use let (block-scoped) or closure ``` The Solution: ```javascript function processOrders(orders) { for (let i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // ✅ Works! }, 1000); } } ``` --- 💡 Senior-Level Insight "Hoisting explains why: · var causes unexpected bugs (always use let/const) · TDZ prevents accessing variables before declaration · Function hoisting enables clean code organization Modern JS best practice: Declare variables at the top. Use const by default, let when reassignment needed." --- 🎤 Interview Answer Structure Q: "Explain hoisting." "Hoisting is JavaScript's compilation-phase behavior where declarations are moved to the top. Function declarations are fully hoisted, var variables hoisted as undefined, while let/const are hoisted but stay in Temporal Dead Zone until execution. This is why we get undefined with var but ReferenceError with let when accessed early." --- 📝 Quick Cheat Sheet Type Hoisted Initial Value Access Before Declaration var ✅ undefined Returns undefined let ✅ Uninitialized ❌ ReferenceError (TDZ) const ✅ Uninitialized ❌ ReferenceError (TDZ) Function Dec ✅ Function itself ✅ Works fine --- 🚨 Common Interview Twist: ```javascript var a = 1; function test() { console.log(a); // undefined (not 1!) var a = 2; } test(); // Why? Inner var a is hoisted to top of function scope ``` --- Master hoisting = Master JavaScript execution. Found this helpful? ♻️ Share with your network. Follow me for more interview prep content! #JavaScript #CodingInterview #WebDevelopment #TechInterview #JSHoisting
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝗦𝗲𝗿𝘃𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 𝗮𝗿𝗲𝗻'𝘁 𝗷𝘂𝘀𝘁 '𝗥𝗲𝗮𝗰𝘁 𝗼𝗻 𝘀𝗲𝗿𝘃𝗲𝗿.' 𝗧𝗵𝗶𝘀 𝗺𝗶𝘀𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗹𝗼𝘀𝘁 𝗮 𝗰𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲 𝘁𝗵𝗲𝗶𝗿 𝗱𝗿𝗲𝗮𝗺 𝗷𝗼𝗯.... The interview was going well. Strong portfolio. Clean code. Solid React fundamentals. Then Question: "What’s the difference between Server Components and SSR?" Candidate: "They both run on the server… so pretty similar." Interview ENDED in 5 minutes. 𝗛𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝗯𝗿𝘂𝘁𝗮𝗹 𝘁𝗿𝘂𝘁𝗵: If you think Server Components are just “React on the server”, you’ve missed the entire point. And in 2026, that costs opportunities. 𝗪𝗵𝗮𝘁 𝗺𝗼𝘀𝘁 𝗱𝗲𝘃𝘀 𝗺𝗶𝘀𝘀: SSR (Server-Side Rendering): • Render on server • Send HTML • Then hydrate on client • Entire component tree ships as JS You still pay the JavaScript cost. 𝗦𝗲𝗿𝘃𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀: • Render on server • Send serialized output • No component code sent to client • Zero JS bundle impact The browser never sees that code. 𝗧𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝘁𝗵𝗮𝘁 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗺𝗮𝘁𝘁𝗲𝗿𝘀: SSR : Render → Hydrate → Ship JS You pay twice. 𝗦𝗲𝗿𝘃𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀: Render → Send output → Done No hydration. No extra JS. 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗰𝗵𝗮𝗻𝗴𝗲𝘀 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴: • Import a 500KB library in SSR → ships to browser • Import it in Server Components → 0KB to client • Fetch data in SSR → API layer needed • Fetch in Server Components → direct DB access Less JS. Faster apps. Simpler architecture. 𝗛𝗼𝘄 𝗺𝗼𝗱𝗲𝗿𝗻 𝗥𝗲𝗮𝗰𝘁 𝗶𝘀 𝗯𝘂𝗶𝗹𝘁: • Server Components → data-heavy, static UI • Client Components → interactivity (state, events) • SSR → initial HTML for fast load You compose them together. 𝗪𝗵𝗮𝘁 𝗯𝗿𝗲𝗮𝗸𝘀 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝘁𝗵𝗶𝘀: • Using useState in Server Components → error • Adding onClick → doesn’t work • Marking everything "use client" → defeats the purpose • Can’t explain trade-offs → weak interview signal 𝗧𝗵𝗲 𝗶𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗳𝗶𝗹𝘁𝗲𝗿: “When would you use Server Components over SSR?” 𝗦𝘁𝗿𝗼𝗻𝗴 𝗮𝗻𝘀𝘄𝗲𝗿: • Reduce JS bundle size • Avoid unnecessary hydration • Fetch data directly on server • Use for non-interactive content 𝗧𝗿𝗮𝗱𝗲-𝗼𝗳𝗳: no hooks, no interactivity 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲: One candidate memorized definitions. The other understood architecture. If you don’t know where to start with concepts like this, my Frontend Interview Resource covers everything step-by-step. Link in comments 👇
To view or add a comment, sign in
-
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming *Double Tap ❤️ For More*
To view or add a comment, sign in
-
🔥 Web Development Interview Questions with Sample Answers — Part 1 🧩 1) Explain your project end-to-end 👉 Answer: “I built a full stack MERN application where users can register, log in, and manage data (like products or tasks). The frontend is built using React, which handles UI and API calls. The backend is built with Node.js and Express, which exposes REST APIs. MongoDB is used to store data. Flow: User interacts with UI → React sends API request → Express handles logic → MongoDB stores/retrieves data → Response is sent → React updates UI.” 🔐 2) How did you implement authentication? 👉 Answer: “I used JWT-based authentication. During signup, passwords are hashed using bcrypt before storing in the database. During login, I verify the password using bcrypt.compare(). If valid, I generate a JWT token and send it to the frontend. Frontend stores the token and sends it in headers for protected API calls.” 🌐 3) How does frontend communicate with backend? 👉 Answer: “Frontend communicates with backend using HTTP requests via fetch or axios. For example, React sends a GET request to /users to fetch data or POST request to /login to authenticate. Backend processes the request and returns JSON response.” ⚠️ 4) How do you handle errors in your application? 👉 Answer: “On the backend, I use try/catch blocks and return proper HTTP status codes like 400, 401, 500. On the frontend, I handle errors using state and show user-friendly messages like ‘Something went wrong’ or validation errors.” 🔄 5) How do you update UI after an API call? 👉 Answer: “After receiving the API response, I update the React state using useState. When state updates, React automatically re-renders the component, which updates the UI.” #WebDevelopment #FrontendDeveloper #JavaScriptProjects #HTML #CSS #RestaurantWebsite #AdminDashboard #CartSystem #LocalStorage #WebDeveloperJourney #BuildInPublic #LearningByDoing #PortfolioProject #CodingLife #SelfTaughtDeveloper
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming
To view or add a comment, sign in
-
💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
🚀 Where to Use Spread (...) and Rest (...) Operators in JavaScript (Real Use Cases) Many developers know spread and rest… But the real question is 👉 Where should you actually use them? 🔹 Spread Operator (...) → “Expand Values” 👉 Use spread when you want to open / copy / merge data 1. Copy Arrays (Avoid Bugs) const arr = [1, 2, 3]; const copy = [...arr]; 👉 Without spread: const copy = arr; // ❌ same reference (danger) 2. Merge Arrays const a = [1, 2]; const b = [3, 4]; const result = [...a, ...b]; 👉 Very common in real apps 3. Update Objects (Immutability – VERY IMPORTANT in React) const user = { name: "Javascript" }; const updatedUser = { ...user, age: 21 }; 👉 Don’t mutate original object 4. Pass Array as Function Arguments const nums = [5, 10, 2]; Math.max(...nums); 5. Clone Objects const newUser = { ...user }; 👉 Used in state updates (React) 🔹 Rest Operator (...) → “Collect Values” 1. Functions with Unlimited Arguments function sum(...numbers) { return numbers.reduce((a, b) => a + b); } 👉 Flexible functions 2. Separate Values from Array const [first, ...rest] = [1, 2, 3, 4]; 👉 Extract first → collect remaining 3. Remove Properties from Object const user = { name: "Javascript", age: 21, city: "Hyd" }; const { name, ...others } = user; 👉 Useful for filtering data 4. Handling API Data const { id, ...userData } = response; 👉 Separate important fields >>>Spread = “Break it apart” >>> Rest = “Bring it together” “Both use ... , how do you differentiate?” It depends on context — >> If it’s expanding values → Spread >> If it’s collecting values → Rest Example: function demo(a, b, ...rest) { console.log(a, b, rest); } const arr = [1, 2, 3, 4]; demo(...arr); #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development