🚀 Just Built a Simple Shopping Cart using JavaScript & LocalStorage! I practiced JavaScript DOM manipulation and LocalStorage by building a small cart system where users can add products with quantities and keep the data saved even after refreshing the page. 💡 Features: • Add product with quantity • Update quantity if product already exists • Store data in LocalStorage • Retrieve stored cart after page reload 🧑💻 Sample Code: const handleAddCart = () => { const productEl = document.getElementById('product') const quantityEl = document.getElementById('quantity') const product = productEl.value; const quantity = parseInt(quantityEl.value); productAddToUl(product, quantity); addToCart(product, quantity) productEl.value = ''; quantityEl.value = ''; } const getCart = () => { let cart = {} const cartJson = localStorage.getItem('cart'); if(cartJson){ cart = JSON.parse(cartJson) } return cart; } const addToCart = (product, quantity) => { const cart = getCart(); if(cart[product]){ cart[product] = cart[product] + quantity; }else{ cart[product] = quantity; } const cartJson = JSON.stringify(cart); localStorage.setItem('cart', cartJson) } #JavaScript #WebDevelopment #FrontendDeveloper #LocalStorage #Coding GitHub Repository:https://lnkd.in/gYrfSkkY
Building a Simple Shopping Cart with JavaScript & LocalStorage
More Relevant Posts
-
Blog 07 of my JS Unlocked series is live! 🚀 Array Methods You Must Know in JavaScript 👇 Arrays store data. But these methods are what make that data actually useful — transform it, filter it, calculate from it. In this one I cover: ✅ push() & pop() — add/remove from the end ✅ shift() & unshift() — add/remove from the front ✅ forEach() — loop through every item cleanly ✅ map() — transform every item into a new array ✅ filter() — keep only what passes the condition ✅ reduce() — combine everything into one value ✅ Visual flowcharts for map, filter & reduce ✅ for loop vs map/filter — side by side comparison Would love your feedback if you read it 🙏 🔗 https://lnkd.in/d26hbMGM Thanks to Hitesh Choudhary Sir, Piyush Garg #JavaScript #WebDevelopment #Hashnode #WebDevCohort2026 #LearningInPublic #Frontend #JS
To view or add a comment, sign in
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
🚀 Day 7 of My JavaScript Journey Today was all about mastering Arrays in JavaScript — one of the most powerful and commonly used concepts in web development 💻🔥 Here’s a quick breakdown of what I learned 👇 📌 What is an Array? Array is a collection of multiple values stored in a single variable. 📌 Basics Access elements using index Find length using .length Arrays can store different data types (heterogeneous) 📌 Mutability Arrays in JavaScript are mutable, meaning we can change their values anytime. 📌 Adding & Removing Elements push() → add at end pop() → remove from end unshift() → add at beginning shift() → remove from beginning ⚠️ Avoid shift() & unshift() in large arrays (performance issue) 📌 Loops for Iteration for loop → more control for...of loop → cleaner & easy 📌 Copying Arrays Copy by reference can cause unexpected changes 👉 Important concept to avoid bugs 📌 const with Arrays You can modify elements even if array is const But cannot reassign the whole array 📌 Array Methods slice() → creates a shallow copy splice() → modifies original array Spread operator ... → merge arrays 📌 Conversions & Searching Convert array to string Search using methods like includes() 📌 Sorting & Reversing Default sort works for strings ❗Fails for numbers → needs custom compare function Custom sorting for ascending & descending order 📌 Advanced Concepts Flatten nested arrays Arrays are actually objects in JavaScript 👉 That’s why they behave differently than "true arrays" in other languages 💡 Key Takeaway: Understanding arrays deeply is super important because they are used everywhere — from handling data to building real-world applications. 🔥 Slowly but consistently improving every day! #javascript #webdevelopment #mernstack #learninginpublic #day7 #codingjourney
To view or add a comment, sign in
-
-
🚀 map(), filter(), reduce() in JavaScript (with Definitions + Examples) (Part:3) These 3 array methods are must-know if you want to get strong in JavaScript Example array: let arr = [1, 2, 3, 4, 5]; 1️⃣ map() → Transform data Definition: map() creates a new array by applying a function to each element. let result = arr.map((num) => num * 2); console.log(result); // [2, 4, 6, 8, 10] ✔️ Use when you want to modify every element 2️⃣ filter() → Select data Definition: filter() creates a new array with elements that satisfy a condition. let result = arr.filter((num) => num > 2); console.log(result); //[3, 4, 5] ✔️ Use when you want to pick specific values 3️⃣ reduce() → Combine data Definition: reduce() reduces the array to a single value by applying a function. let result = arr.reduce((acc, num) => acc + num, 0); console.log(result); // 15 ✔️ Use for sum, totals, complex calculations Key Differences: >> map → transforms each element >> filter → selects elements >> reduce → combines into one value 🎯 Important Note: >>> These methods do not change the original array (they return a new one) # forEach() vs map() : 1️⃣ forEach() >> Executes a function for each element >> Does NOT return anything let result = arr.forEach((num) => { return num * 2; }); console.log(result); // undefined 2️⃣ map() >> Transforms each element >> Returns a NEW array let result = arr.map((num) => num * 2); console.log(result); // [2, 4, 6] #JavaScript #Frontend #WebDevelopment #Coding #LearnInPublic
To view or add a comment, sign in
-
🚀 Web APIs in JavaScript If JavaScript is single-threaded… 👉 How does it handle setTimeout, fetch, or click events without freezing? The answer is Web APIs. What are Web APIs? 👉They are built-in features provided by the browser that allow JavaScript to interact with the web page and the outside world. 1. DOM API (Document Object Model) This lets you interact with HTML elements. ✔️ Change content ✔️ Add/remove elements ✔️ Handle user actions Example: document.getElementById("title").innerText = "Hello World!"; 2. Fetch API Used to get data from servers (APIs). ✔️ Fetch data from backend ✔️ Work with JSON ✔️ Build dynamic apps Example: fetch("https://lnkd.in/dQeGAVaB") .then(res => res.json()) .then(data => console.log(data)); 3. Timer APIs Helps you control time-based execution. ✔️ setTimeout → run once after delay ✔️ setInterval → run repeatedly Example: setTimeout(() => console.log("Hello after 2 sec"), 2000); 4. Geolocation API Access user's location (with permission). ✔️ Latitude & Longitude ✔️ Location-based apps 5. Web Storage API Store data in the browser. ✔️ localStorage (permanent) ✔️ sessionStorage (temporary) Example: localStorage.setItem("user", "Kavi"); 6. Event Handling API Respond to user actions like clicks, typing, etc. Example: button.addEventListener("click", () => { console.log("Button clicked!"); }); >>JavaScript is single-threaded, but Browser APIs + Event Loop make it feel asynchronous! #JavaScript #WebDevelopment #Frontend #Programming #BrowserAPIs #100DaysOfCode
To view or add a comment, sign in
-
This article provides a comprehensive step-by-step guide on creating a barcode generator using JavaScript, which is essential for developers working on inventory systems and internal tools. I found it interesting that the author breaks down the process so clearly, making it accessible even for those new to JavaScript. What barcode-related projects are you currently working on, or have you found similar tools useful in your past experiences?
To view or add a comment, sign in
-
🚀 Day 14/30 – Forms in React (Deep Dive) Still confused why React forms feel different from HTML? 👀 Today I learned how React actually handles user input ⚡ 👉 Forms in React Today I learned: ✅ React controls form inputs using state ✅ Every input change triggers re-render ✅ Forms follow a “single source of truth” 💻 Example: import { useState } from "react"; function Form() { const [name, setName] = useState(""); return ( <> <input value={name} onChange={(e) => setName(e.target.value)} /> <h2>Hello {name}</h2> </> ); } 🔥 What actually happens behind the scenes: 1️⃣ User types → onChange fires 2️⃣ React updates state 3️⃣ Component re-renders 4️⃣ Input value stays in sync with state 👉 This is why React forms feel “controlled” 💡 Controlled vs Uncontrolled (Important): 👉 Controlled Component ✅ - Value comes from state - Fully controlled by React - Easy validation & debugging 👉 Uncontrolled Component ⚡ - Value stored in DOM (useRef) - Less React control - Used in rare cases 💻 Example (Uncontrolled): const inputRef = useRef(); <input ref={inputRef} />⚡ Real Use Cases: - Login / Signup forms - Form validation (required, regex, etc.) - Search inputs with live updates ⚡ Advanced Insight: React forms = continuous sync between UI & state (not like traditional HTML forms) 🔥 Key Takeaway: If state and input are not synced → your form is broken. Are you building controlled forms or still mixing both? 👇 #React #Forms #FrontendDevelopment #JavaScript #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript prototypes clicked for me the moment I stopped thinking about copying and started thinking about linking. Here's the mental model that made it stick 👇 🔹 The core idea Every object in JavaScript has a hidden link to another object — its prototype. When you access a property, JS doesn't just look at the object itself. It walks the chain: Check the object Not found? Check its prototype Still not found? Check the prototype's prototype Keep going until null That's the prototype chain. Simple as that. 🔹 See it in action jsconst user = { name: "Aman" }; const admin = { isAdmin: true }; admin.__proto__ = user; console.log(admin.name); // "Aman" ✅ admin doesn't have name — but JS finds it one level up. 🔹 Why constructor functions use this jsfunction User(name) { this.name = name; } User.prototype.sayHi = function () { console.log(`Hi, I am ${this.name}`); }; Every User instance shares one sayHi method. Not copied — linked. That's free memory efficiency, built into the language. 🔹 Two things worth keeping straight prototype → a property on constructor functions __proto__ → the actual link on any object The modern, cleaner way to set that link: jsconst obj = Object.create(user); 🔹 Why bother understanding this? Because it shows up everywhere — class syntax, frameworks, unexpected undefined bugs, performance decisions. Prototypes aren't a quirk. They are the inheritance model. One line to remember: JS doesn't copy properties. It searches a chain of linked objects. #JavaScript #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝗔𝗿𝗿𝗼𝘄 𝗙𝘂𝗻𝗰𝗍𝗶𝗼𝗻𝘀 You've seen the => symbol in JavaScript code. It's called an Arrow Function. - Makes your code look sleeker - Reduces "boilerplate" code Let's look at an example: squaring a number. You can write it like this: const square = function(n) { return n * n; }; Or like this: const square = (n) => { return n * n; }; We removed the word "function" and added => after the parameters. If your function only needs one parameter, you can drop the parentheses. const square = n => { return n * n; }; If your function needs more than one parameter, you add the parentheses back. const multiply = (a, b) => { return a * b; }; console.log(multiply(5, 4)); // Output: 20 The coolest part of Arrow Functions is Implicit Return. If your function only has one line of code, you can throw away the curly braces and the return keyword. const add = (a, b) => a + b; Arrow functions are perfect for methods like map(). Check an array of numbers and return if they are "Even" orOdd.const numbers = [1, 2, 3, 4]; const checkNumbers = numbers.map(num => num % 2 === 0 ? "Even : Odd"); console.log(checkNumbers); // ["Odd", "Even", "Odd", "Even"] Arrow functions make your code shorter, easier to read, and more expressive. They help you write functions quickly and make your code easier for other developers to understand. Source: https://lnkd.in/gh_-Skrh
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