In JavaScript, we often use if...else if...else chain to handle conditions. But, there is a cleaner way to write this code, objects. For example, look at the following code: for (tab in issueElems) { if (tab === "open") { openIssues.innerHTML = ""; openCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, openIssuesSpinner); } else if (tab === "closed") { closedIssues.innerHTML = ""; closedCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, closedIssuesSpinner); } else { allIssues.innerHTML = ""; allCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, allIssuesSpinner); } } Now, if we define an object like the following beforehand: let issueElems = { all: { count: allIssuesCount, issues: allIssues, spinner: allIssuesSpinner, }, open: { count: openIssuesCount, issues: openIssues, spinner: openIssuesSpinner, tab: openTab, }, closed: { count: closedIssuesCount, issues: closedIssues, spinner: closedIssuesSpinner, tab: closedTab, }, }; The code becomes as simple as this: for (tab in issueElems) { let c = issueElems[tab]; c.issues.innerHTML = ""; c.count.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, c.spinner); } There is also switch...case, but it works in a very absurd way. If you don't add break to case clauses, it keeps going to the next case clause. It starts with the first matching case clause and continues until the break statement is encountered. That's why objects are the best way to handle this matter. What do you use? Share your ideas!
JavaScript Simplified: Using Objects for Conditional Logic
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
-
🚀 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>
To view or add a comment, sign in
-
Most bugs don’t come from complex logic — they come from misunderstood behavior. One classic example in JavaScript: **shallow copy vs deep copy**. If you’ve worked with objects long enough, you’ve probably seen unexpected mutations. That usually comes down to how copying actually works under the hood. 🔹 SHALLOW COPY — copies structure, not depth Common methods: spread operator `{...obj}`, `Object.assign()`, array `slice()` / `concat()` ✔️ Creates a new top-level object ❌ Nested objects/arrays still share references ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const copy = { ...user }; copy.prefs.theme = "light"; console.log(user.prefs.theme); // "light" ``` Even though `copy` looks independent, the nested object is still pointing to the same memory. 🔸 DEEP COPY — full separation Modern approach: `structuredClone()` ✔️ Completely independent copy ✔️ Handles nested objects, arrays, Map, Set, Date, etc. ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const clone = structuredClone(user); clone.prefs.theme = "light"; console.log(user.prefs.theme); // "dark" ``` Quick comparison • `{...spread}` → shallow • `Object.assign()` → shallow • `structuredClone()` → deep ✅ • `JSON.parse(JSON.stringify())` → deep ⚠️ (drops Date, undefined, functions) • `_.cloneDeep()` → deep ✅ (useful for legacy support) When should you use what? → Flat data (no nesting)? Shallow copy is enough → Nested structures? Go for deep copy → Working with Date, Map, Set? Prefer `structuredClone()` → Need wide browser support? Use `_.cloneDeep()` Simple rule: If your data has depth, your copy should too. #JavaScript #WebDevelopment #Frontend #CodingTips #JS #SoftwareEngineering #Programming
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
-
𝗧𝗵𝗲 𝗨𝗹𝗧𝗶𝗺𝗮𝗧𝗲 𝗚𝗨𝗶𝗱𝗲 𝗧𝗼 𝗕𝗨𝗶𝗟𝗗𝗶𝗡𝗚 𝗔 𝗖𝗨𝗦𝗧𝗢𝗠 𝗠𝗢𝗗𝗨𝗟𝗘 𝗟𝗢𝗔𝗗𝗘𝗥 You want to build a custom module loader for browser environments. This is a comprehensive guide to help you get started. Here's what you need to know: - JavaScript modules have evolved over time. - You can use ES Modules, CommonJS, AMD, or UMD. - A custom module loader gives you control over module resolution and loading. You can build a basic module loader using a class: - Define modules with a name and function. - Require modules by name and cache them. For example: ```javascript class ModuleLoader { constructor() { this.modules = {}; this.cache = {}; } define(name, moduleFunction) { this.modules[name] = moduleFunction; } require(name) { if (this.cache[name]) { return this.cache[name]; } if (!this.modules[name]) { throw new Error(`Module ${name} is not defined.`); } const moduleExports = {}; const module = { exports: moduleExports }; this.modules[name].call(module, moduleExports, this.require.bind(this)); this.cache[name] = module.exports; return module.exports; } } ``` You can also build an advanced module loader with dependencies: - Define modules with a name, dependencies, and function. - Require modules by name and resolve dependencies. For example: ```javascript class AdvancedModuleLoader { constructor() { this.modules = {}; this.cache = {}; } define(name, dependencies, moduleFunction) { this.modules[name] = { dependencies, moduleFunction }; } require(name) { if (this.cache[name]) { return this.cache[name]; } if (!this.modules[name]) { throw new Error(`Module ${name} is not defined.`); } const { dependencies, moduleFunction } = this.modules[name]; const resolvedDependencies = dependencies.map(dep => this.require(dep)); const moduleExports = {}; const module = { exports: moduleExports }; moduleFunction.call(module, moduleExports, ...resolvedDependencies); this.cache[name] = module.exports; return module.exports; } } ``` You can use lazy loading to improve performance: - Define modules with a name and function. - Require modules by name and cache them. For example: ```javascript class LazyLoader { constructor() { this.modules = {}; this.cache = {}; } define(name, moduleFunction) { this.modules[name] = moduleFunction; } require(name) { return new Promise((resolve, reject) => { if (this.cache[name]) { return resolve(this.cache[name]); } if (!this.modules[name]) { return reject(new Error(`Module ${name} is not defin
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 37 Till now… you’ve written all your JavaScript in one file 😵 👉 Everything mixed together 👉 Hard to manage 👉 Hard to scale What if you could **split your code into multiple files** and still use them together? 🤔 --- ## 🔥 Solution → Modules --- ## 🔹 What are Modules? Modules allow you to: 👉 Break code into **separate files** 👉 Reuse code easily 👉 Keep code clean & organized --- ## 🔹 Exporting Code ```javascript id="md1" // math.js export function add(a, b) { return a + b } ``` 👉 `export` makes function available outside --- ## 🔹 Importing Code ```javascript id="md2" // main.js import { add } from "./math.js" console.log(add(5, 3)) ``` 👉 Output: 8 --- ## 🔹 Default Export ```javascript id="md3" // user.js export default function greet() { console.log("Hello") } ``` Import: ```javascript id="md4" import greet from "./user.js" ``` --- ## 🔥 Real Life Example Think of a big project 🏢 👉 One file → login 👉 One file → dashboard 👉 One file → API All connected… but separate --- ## 🔥 Why Modules Matter? ✅ Clean code ✅ Reusable logic ✅ Easy to maintain ✅ Scalable projects --- ## 🔥 Simple Summary export → share code import → use code modules → organize code --- ### 💡 Programming Rule **Divide your code. Organize it. Scale it.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules Day 38 → Debounce (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🔑 JavaScript Maps – Quick Guide 1. What is a Map? A collection of key‑value pairs (like a dictionary). Keys can be any type (string, number, object, etc). Preserves insertion order. Optimized for frequent additions/removals. Iterable → can use for...of and forEach() directly. 2. Creating Maps // Empty Map + set() const fruits = new Map(); fruits.set("apples", 500); fruits.set("bananas", 300); // From array const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); 3. Core Methods MethodPurposeExampleReturns set(key, value)Add/change valuefruits.set("mangos", 100)Updated Map get(key)Retrieve valuefruits.get("apples")500 delete(key)Remove entryfruits.delete("bananas")Boolean has(key)Check existencefruits.has("oranges")true/false clear()Remove all entriesfruits.clear()Empty Map sizeCount entriesfruits.sizeNumber 4. Iteration // for...of for (const [key, value] of fruits) { console.log(key, value); } // forEach fruits.forEach((value, key) => { console.log(key, value); }); 5. Map vs Object FeatureObjectMap IterationNot directly iterable✅ Directly iterable SizeNo size property✅ .size Key typesStrings/Symbols only✅ Any datatype OrderNot guaranteed✅ Insertion order preserved Default keysPrototype keys exist✅ No default keys 6. Type & Identity typeof fruits; // "object" fruits instanceof Map; // true 📝 Exercise Answer Which method can be used to add elements to a Map? 👉 Correct answer: set() 🎯 Memory Hook Think of a Map as a super‑powered Object: Any type of key. Ordered. Easy to count with .size. Perfect for dictionaries, caches, and lookups.
To view or add a comment, sign in
-
Never be afraid to clarify the meaning of words you don't fully understand. And never hesitate to revisit topics that seem «obvious» — even after years of experience. I asked my student: «What data types exist in PHP?» He started listing int, float, string, resource... callable(?). I stopped him right there and said that callable is not a data type, then went to back it up with the PHP documentation. And found this: https://lnkd.in/dWUAkPev «Every single expression in PHP has one of the following built-in types depending on its value: null, bool, int, float, string, array, object, callable, resource» That surprised me. I knew that a variable in PHP cannot have the type callable. Looking here https://lnkd.in/d942QF9P — it clearly states that a callable can be created in several ways: • A Closure object • A string containing a function or method name • An array with a class name or object at index 0 and the method name at index 1 • An object implementing the __invoke() magic method When we talk about data types in programming languages, what matters is that we can store a value of that type in a variable. But here, a variable for which is_callable() returns true will actually be one of the types listed above. In other words, the following code returns true: ```php declare(strict_types=1); function foo(): string { return 'hello'; } $f = 'foo'; var_dump(is_callable($f)); // bool(true) ``` It will also pass a type hint: ```php declare(strict_types=1); function foo(): string { return 'hello'; } function bar(callable $f): string { return $f(); } $f = 'foo'; var_dump(bar($f)); // string(5) "hello" ``` And $f is still just a plain string — you can manipulate it like one: ```php // ... (foo declaration, $f = 'foo') $f .= ' Hello LinkedIn'; var_dump($f); // string(19) "foo Hello LinkedIn" ``` So callable is not a standalone data type — it's a predicate over multiple types: string, array, and object. For someone just learning PHP, seeing callable in the list of types can be genuinely confusing. Don't hesitate to question the basics — the answer isn't always obvious. #PHP #Programming #SoftwareDevelopment #Backend #CodeQuality
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 33 You wrote a function… It finished execution… But somehow 😳 👉 It still remembers old variables? How is that possible? 🤯 --- ## 🔥 This is called → Closures --- ## 🔹 What is a Closure? A **closure** is when a function 👉 Remembers variables from its outer scope 👉 Even after the outer function has finished --- ## 🔹 Example ```javascript id="cl1" function outer() { let count = 0 return function inner() { count++ console.log(count) } } let counter = outer() counter() counter() counter() ``` 👉 Output: 1 2 3 --- ## 🔍 What’s happening? 👉 `outer()` executed once 👉 `inner()` still remembers `count` 👉 Value persists 😎 --- ## 🔥 Why is this powerful? Because function can **remember state** --- ## 🔹 Real Life Example Think of a **bank account 🏦** ```javascript id="cl2" function bankAccount() { let balance = 1000 return function deposit(amount) { balance += amount console.log(balance) } } let account = bankAccount() account(500) account(200) ``` 👉 Output: 1500 1700 👉 Balance remembered between calls --- ## 🔥 Where are closures used? 👉 Data privacy 👉 Counters 👉 Event handlers 👉 React hooks --- ## 🔥 Simple Summary Closure → function + memory Remembers outer variables Keeps state alive --- ### 💡 Programming Rule **Closures give functions memory. Use them to control data smartly.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototype (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
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