🚀 30 Days of JavaScript – Day 20 Today I upgraded my To-Do App with more advanced features. 💡 Project: Advanced To-Do App New features added: • Mark tasks as completed • Edit existing tasks • Delete tasks • Store data using localStorage 🧠 Concepts Used: • DOM manipulation • CRUD operations • local Storage • dynamic UI updates 📌 This project helped me understand how real applications manage and update data. 🎥 Demo below 👇 👉 Source code in (only JS Code). #JavaScript #FrontendDevelopment #WebDevelopment #LearningJavaScript #CodingJourney <script> let tasks = JSON.parse(localStorage.getItem("tasks")) || []; function showTasks() { let list = document.getElementById("taskList"); list.innerHTML = ""; tasks.forEach((task, index) => { let li = document.createElement("li"); let text = document.createElement("span"); text.innerText = task.name; if (task.completed) { text.classList.add("completed"); } // actions let actions = document.createElement("div"); actions.className = "actions"; // complete button let completeBtn = document.createElement("button"); completeBtn.innerText = "✔"; completeBtn.onclick = function() { toggleComplete(index); }; // edit button let editBtn = document.createElement("button"); editBtn.innerText = "Edit"; editBtn.onclick = function() { editTask(index); }; // delete button let deleteBtn = document.createElement("button"); deleteBtn.innerText = "X"; deleteBtn.onclick = function() { deleteTask(index); }; actions.appendChild(completeBtn); actions.appendChild(editBtn); actions.appendChild(deleteBtn); li.appendChild(text); li.appendChild(actions); list.appendChild(li); }); } function addTask() { let input = document.getElementById("taskInput"); if (input.value === "") { alert("Enter task"); return; } tasks.push({ name: input.value, completed: false }); localStorage.setItem("tasks", JSON.stringify(tasks)); input.value = ""; showTasks(); } function deleteTask(index) { tasks.splice(index, 1); localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } function toggleComplete(index) { tasks[index].completed = !tasks[index].completed; localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } function editTask(index) { let newTask = prompt("Edit your task:", tasks[index].name); if (newTask !== null && newTask !== "") { tasks[index].name = newTask; localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } } showTasks(); </script>
More Relevant Posts
-
#SoftwareEngineer_Not_Code_Monkey I was recently revisiting some concepts that used to trip me up in JavaScript: Array Manipulation. Sometimes, the best way to master a concept is to lay them all out, look them in the eye, and have a little "chat" with the code. Yes, I talk to my code—and you should too! Let’s break down the "Internal Dialogue" of a Senior Developer when handling arrays: .map() — The Transformer The Conversation: "Take this array, visit every single element, and give me a new array with the modifications I asked for. Same length, fresh look." Use Case: Formatting currency or wrapping data in UI components. JavaScript const prices = [10, 20, 30]; const formattedPrices = prices.map(price => `$${price}.00`); // Result: ["$10.00", "$20.00", "$30.00"] .filter() — The Gatekeeper The Conversation: "I’ve got a condition. Check every item; if they pass, they join the new array. If they fail? They’re out." Use Case: Removing "Out of Stock" items or finding "Admin" users. .reduce() — The Grinder The Conversation: "Take the whole list, start with this 'bag' (Accumulator) set to 0, and squash everything down into one single value." Use Case: Calculating a shopping cart total or flattening nested data. JavaScript const cart = [100, 200, 300]; const total = cart.reduce((acc, price) => acc + price, 0); // Result: 600 .find() — The Scout The Conversation: "Go find me the first person named 'Ashraf'. Once you find him, stop looking and bring him back to me—not a list, just the man himself." const students = ["Ahmed", "Ashraf", "Sara"]; const winner = students.find(s => s === "Ashraf"); // Result: "Ashraf" .forEach() — The Blue-Collar Worker The Conversation: "Don't give me a new array. Just loop through and do something—log it, send it to an API, or trigger an alert." const tasks = ["Task 1", "Task 2"]; tasks.forEach(task => console.log(`Processing: ${task}`)); .some() & .every() — The Inspectors .some(): "Is there at least one rebel in this list? If yes, give me a true." .every(): "Is everyone following the rules? If even one person fails, give me a false." The Engineer's Takeaway: Immutability Except for forEach and sort, these methods respect the Immutability principle. We don't touch the original array—it’s a "Red Line." We create new versions. This keeps your state predictable and your bugs minimal, especially as your project scales from a simple script to a full-blown freelance system. Stop just "writing code." Start engineering solutions. Which Array method was your "final boss" when you started? #Programming #SoftwareEngineering #JavaScript #CleanCode #WebDevelopment #Frontend #TechCommunity #ReactJS #NodeJS #Freelancing
To view or add a comment, sign in
-
🔑 JavaScript Set Reference – Quick Guide 1. Creation js const mySet = new Set(); // empty const letters = new Set(["a","b","c"]); // from array 2. Core Methods MethodPurposeExampleReturnsadd(value)Add elementmySet.add("x")Updated Setdelete(value)Remove elementmySet.delete("a")Booleanclear()Remove all elementsmySet.clear()Empty Sethas(value)Check existencemySet.has("b")true/falsesizeCount elementsmySet.sizeNumber 3. Iteration Methods MethodPurposeExampleforEach(callback)Run function for each valuemySet.forEach(v => console.log(v))values()Iterator of valuesfor (const v of mySet.values()) {}keys()Same as values()mySet.keys()entries()Iterator of [value, value] pairsmySet.entries() 4. Set Logic Methods (ES2025+) MethodPurposeunion(otherSet)Combine elements of both setsintersection(otherSet)Common elementsdifference(otherSet)Elements in one set but not the othersymmetricDifference(otherSet)Elements in either set but not bothisSubsetOf(otherSet)True if all elements are in other setisSupersetOf(otherSet)True if contains all elements of other setisDisjointFrom(otherSet)True if no common elements 5. Example Usage js const a = new Set([1,2,3]); const b = new Set([3,4,5]); console.log(a.union(b)); // {1,2,3,4,5} console.log(a.intersection(b)); // {3} console.log(a.difference(b)); // {1,2} console.log(a.symmetricDifference(b));// {1,2,4,5} 6. Key Notes Unique values only → duplicates ignored. Insertion order preserved. Sets are iterable (unlike WeakSets). Useful for mathematical set operations and fast membership checks. 🎯 Memory Hook Think of a Set as a mathematical set in code: No duplicates. Easy union/intersection/difference. Fast membership checks with .has().
To view or add a comment, sign in
-
🚀 Fetch vs Axios in JavaScript When building modern web applications, interacting with APIs is a daily task. Two of the most commonly used tools for this are Fetch and Axios. 🔹 What is fetch()? Definition: fetch() is a built-in Web API in JavaScript used to make HTTP requests to servers and retrieve resources. 👉 It is promise-based and available in all modern browsers. 📌 How Fetch Works >> Sends a request to a server (GET, POST, etc.) >> Returns a Promise >> Resolves to a Response object >> You must extract data manually (e.g., .json()) 💻 Example async function fetchData() { try { const response = await fetch("https://lnkd.in/dQeGAVaB"); // Checking response status manually if (!response.ok) { throw new Error("HTTP error! Status: " + response.status); } // Convert response into JSON const data = await response.json(); console.log(data); } catch (error) { console.error("Fetch Error:", error); } } ⚠️ Important Characteristics of Fetch ✔️ Built into browser (no installation) ✔️ Returns Promise ✔️ Requires manual JSON parsing ✔️ Does NOT throw errors for HTTP failures (you must handle it) ✔️ Slightly more verbose 🔹 What is axios? Definition: axios is a third-party JavaScript library used to make HTTP requests from the browser or Node.js. 👉 It is also promise-based but provides many additional features out of the box. 📌 How Axios Works >> Sends HTTP requests (GET, POST, PUT, DELETE, etc.) >> Automatically transforms response into JSON >> Automatically throws errors for bad status codes >> Provides advanced configuration options 💻 Example import axios from "axios"; async function fetchData() { try { const response = await axios.get("https://lnkd.in/dQeGAVaB"); // Axios directly gives data console.log(response.data); } catch (error) { console.error("Axios Error:", error); } } ⚠️ Important Characteristics of Axios ✔️ Requires installation (npm install axios) ✔️ Automatic JSON transformation ✔️ Better error handling ✔️ Supports interceptors (modify request/response globally) ✔️ Supports timeout, cancellation, headers easily ✔️ Cleaner and shorter syntax 💡 When to Use Fetch vs Axios? 👉 Use Fetch when: >> You want a lightweight solution >> No external dependencies required >> Working on small/simple projects 👉 Use Axios when: >> You are building real-world applications >> Need better error handling >> Want features like: >>Interceptors, Global configuration, Request cancellation #JavaScript #WebDevelopment #Axios #FetchAPI #Frontend #Programming #Developers #Coding
To view or add a comment, sign in
-
Symbols were the way to create private fields in JavaScript before private fields were a standard language feature. And in some cases, they're still the best option out there for performance purposes. How do they work? Instead of creating a regular string like "my-key", you create a symbol like `Symbol("my-key")`. The value that `Symbol` returns is unique, meaning that `Symbol("my-key") !== Symbol("my-key")`. This means that a developer can't access your class field using `obj[Symbol("my-key")]`. Rather, only those who have a reference to the uniquely-created symbol can access the field. Consider this code: const key = Symbol("my-key"); obj[key] = "value"; // ... export { obj }; Here, we export `obj`, but not `key`, meaning only we have the ability to read and write the value (kind of). The `ws` Node.js package has been using this clever approach for a long time. Since private fields are a native feature in JS now, there usually isn't a reason to take this approach. However, you might still find it useful when making Custom Elements, or other kinds of classes that need to use event listeners (e.g., in Node). If you remember, I made a post wayyyyyy back explaining how static event listeners provide the best performance in JavaScript. Of course, static event listeners prevent you from accessing `this`. And if you need access to a private field in your event listener, you'll be forced to use `this#key` and lose the performance boost. This is where Symbols shine! Instead of accessing private data through `this#key`, you can access it through `instance[symbolKey]`! As long as you have access to the symbol in your class's file, you'll be able to access data that the rest of the outside world can't (kind of). If you've been catching my "kind of"s, there's a caveat here: JS gives developers a way to inspect all of an object's Symbols. Generally speaking, most developers don't know about the existence of the global function that allows this, and many don't even know about Symbols at all. Plus, Symbol-based properties don't show up in IDE IntelliSense as devs type. So Symbol-based fields are semi-private! Nonetheless, Symbol-based properties are not "perfectly private". You might still choose to use them for performance purposes. But the adventurous devs who love scrutinizing code to find and use the `_DO_NOT_USE` properties will still be able to have their way. As with all things, this is about trade-offs. In my Combobox component, I've mostly been using private fields. But I've reached for Symbols in cases where I really wanted to keep using static event handlers. ComboBoxedIn Logs #17 (No, I haven't forgotten about these.)
To view or add a comment, sign in
-
Day 4: Why doesn't JavaScript get confused? 🧩 Variable Environments & The Call Stack(How Functions works in JS) Today I explored how JavaScript handles multiple variables with the same name across different functions. Using the code below, I took a deep dive into the Variable Environment and the Call Stack. 💻 The Code Challenge: javascript var x = 1; a(); b(); console.log(x); function a() { var x = 10; console.log(x); } function b() { var x = 100; console.log(x); } 🧠 The "Behind the Scenes" Logic: 1️⃣ Global Execution Context (GEC): Memory Phase: x is set to undefined. Functions a and b are stored entirely. Execution Phase: x becomes 1. Then, a() is invoked. 2️⃣ The Function a() Context: A brand new Execution Context is created and pushed onto the Call Stack. This context has its own Variable Environment. The x inside here is local to a(). It logs 10, then the context is popped off the stack and destroyed. 3️⃣ The Function b() Context: Same process! A new context is pushed. Its local x is set to 100. It logs 100, then it's popped off the stack. 4️⃣ Back to Global: Finally, the last console.log(x) runs in the Global context. It looks at the GEC’s Variable Environment where x is still 1. 📚 Key Learnings: Variable Environment: Each execution context has its own "private room" for variables. The x in a() is completely different from the x in the Global scope. Call Stack: It acts as the "Manager," ensuring the browser knows exactly which execution context is currently running. Independence: Functions in JS are like mini-programs with their own memory space. This is the foundation for understanding Lexical Scope and Closures! Watching this happen live in the browser's "Sources" tab makes you realize that JS isn't "magic"—it's just very well-organized! 📂 #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingTips #FrontendEngineer #CodingLogic
To view or add a comment, sign in
-
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
To view or add a comment, sign in
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
Day 99 of me reading random and basic but important dev topicsss.... Today I read about the Scaling Cancellations in JavaScript..... Yesterday, I read how to cancel a single fetch() request using AbortController to prevent memory leaks and UI bugs. But what if we're building a complex dashboard loading dozens of widgets simultaneously? Good news is AbortController is highly scalable.... You don’t need to instantiate a new controller for every single request. A single AbortController signal can be passed to multiple fetch calls. If the user hits "Cancel" or navigates away, calling controller.abort() once will instantly kill all associated network requests! const controller = new AbortController(); const urls = ['/api/users', '/api/analytics', '/api/settings']; // Map URLs to fetch promises, all sharing the same exact signal const fetchJobs = urls.map(url => fetch(url, { signal: controller.signal }) ); try { const results = await Promise.all(fetchJobs); console.log("All data loaded successfully!"); } catch (err) { if (err.name === 'AbortError') { console.log(" ALL parallel requests were aborted instantly!"); } } // Call this from anywhere in your app to cancel everything: // controller.abort(); Note: It's not just for fetch...... You don't have to limit yourself to network requests. AbortController is an elegant, universal event bus for cancellation. You can integrate it into your own custom asynchronous tasks. Since controller.signal emits a standard event, all you need to do is listen for the 'abort' event within your custom Promise: const ourCustomJob = new Promise((resolve, reject) => { // ... Heavy background task logic here ... // Tie your custom task to the same controller controller.signal.addEventListener('abort', () => { reject(new Error("Custom Job Aborted!")); }); }); // Now Promise.all([ ...fetchJobs, ourCustomJob ]) can ALL be managed together! By standardizing cancellation across your app using AbortController, you ensure clean garbage collection, eliminate race conditions, and drastically save your users' network bandwidth. Keep Learning!!!! #JavaScript #AsyncProgramming #WebDev #SoftwareEngineering #CleanCodee
To view or add a comment, sign in
-
-
🚀 Day 24 – Functions & Advanced Concepts in JavaScript Today’s focus is not just theory — it’s how these concepts are used in REAL applications 👇 🔹 1. Debounce 👉 Executes function only after user stops triggering it for a delay. function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Real-time scenario: In an e-commerce website, when a user searches for a product, we don’t call API on every keystroke. Instead, we wait until the user stops typing → then trigger API. 👉 Prevents 20+ unnecessary API calls! 🔹 2. Throttle 👉 Ensures function runs only once in a given interval. function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; flag = false; fn.apply(this, args); setTimeout(() => { flag = true; }, limit); }; } Real-time scenario: While scrolling Instagram/LinkedIn feed, scroll events fire continuously. Throttle ensures smooth performance by limiting executions. 👉 Prevents UI lag & improves performance 🔹 3. Currying 👉 Converts multiple arguments into nested functions. function curry(a) { return function (b) { return function (c) { return a + b + c; }; }; } console.log(curry(2)(3)(4)); // 9 Real-time scenario: In large apps, we create reusable utility functions. Example: Tax calculator → instead of passing all values every time, we reuse partial functions. 👉 Helps in clean & reusable code 🔹 4. Memoization 👉 Caches results to avoid recalculating. function memoize(fn) { const cache = {}; return function (n) { if (cache[n]) return cache[n]; const result = fn(n); cache[n] = result; return result; }; } Real-time scenario: In dashboards (finance/analytics apps), heavy calculations run repeatedly. Memoization stores results → avoids recomputation. 🔹 5. Closures ⭐ 👉 A function remembers variables from its outer scope even after execution. function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Real-time scenario: ✔ Data hiding ✔ Maintaining state (like counters, caches) Used in: ✔ Counters (cart items count) ✔ Private variables (data hiding) ✔ setTimeout inside loops 👉 Helps maintain state without global variables 🔹 6. Pure Functions 👉 Function that always returns same output for same input and has no side effects. function add(a, b) { return a + b; } Real-time scenario: In state management (Angular/React), pure functions ensure predictable updates. Why important? ✔ Predictable ✔ Easy to test ✔ Used in frameworks like Angular & React 👉 Easier debugging & testing #JavaScript #FrontendDeveloper #Angular #InterviewPrep #Coding #WebDevelopment
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