Most developers reach for IDs, classes, or extra state before remembering this: JavaScript already gives you a clean way to attach structured metadata directly to DOM elements. If you have ever used data-* attributes in HTML, you can access them in JavaScript through the dataset property. No parsing. No brittle string manipulation. No unnecessary DOM lookups. It is simple, readable, and surprisingly underused. This pattern is especially useful for event delegation, lightweight UI state, dynamic lists, and keeping behaviour close to the element it belongs to. Small details like this make frontend systems cleaner and easier to reason about without introducing extra abstractions. Not everything needs global state. Sometimes the platform already solved the problem. In the example attached, notice how `data-user-id` becomes `dataset.userId`. Hyphenated attributes automatically convert to camelCase. It is a small feature, but small features compound into cleaner, more maintainable frontend code. What is one underrated JavaScript feature you think more developers should use? Github Gist: https://lnkd.in/d6pjMP7J #webdevelopment #javascript #cleancode
Accessing HTML data-* attributes in JavaScript with dataset property
More Relevant Posts
-
A lot of developers think 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴, 𝗳𝗲𝘁𝗰𝗵, 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 are part of JavaScript. 𝗧𝗵𝗲𝘆’𝗿𝗲 𝗻𝗼𝘁. They’re 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 — provided by the browser (or runtime) to the 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗲𝗻𝗴𝗶𝗻𝗲. JavaScript itself? It’s a 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱, 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 language. 𝗧𝗶𝗺𝗲, 𝗧𝗶𝗱𝗲 𝗮𝗻𝗱 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 𝘄𝗮𝗶𝘁 𝗳𝗼𝗿 𝗻𝗼𝗻𝗲 - A Wise Man (Idk who said it but I'm sure he was wise) So how does async work? 👇 • The JS engine executes code line by line. • When it hits 𝗳𝗲𝘁𝗰𝗵 𝗼𝗿 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁, 𝘁𝗵𝗲 𝗯𝗿𝗼𝘄𝘀𝗲𝗿 𝘁𝗮𝗸𝗲𝘀 𝗼𝘃𝗲𝗿. • Once the task completes, the result is pushed to the event loop - can be the 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲 𝗼𝗿 𝘁𝗵𝗲 𝗠𝗮𝗰𝗿𝗼. • The callback/promise gets executed when the 𝗰𝗮𝗹𝗹 𝘀𝘁𝗮𝗰𝗸 𝗶𝘀 𝗳𝗿𝗲𝗲. So technically… JavaScript isn’t “naturally asynchronous” It’s synchronous — powered by async capabilities from its environment. 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗿𝘂𝗻𝘁𝗶𝗺𝗲𝘀 = 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗔𝗣𝗜𝘀. Browser ≠ Node ≠ Deno A few more 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 we use often - 𝘥𝘰𝘤𝘶𝘮𝘦𝘯𝘵, 𝘸𝘪𝘯𝘥𝘰𝘸, 𝘩𝘪𝘴𝘵𝘰𝘳𝘺, 𝘭𝘰𝘤𝘢𝘵𝘪𝘰𝘯, 𝘭𝘰𝘤𝘢𝘭𝘚𝘵𝘰𝘳𝘢𝘨𝘦, 𝘴𝘦𝘴𝘴𝘪𝘰𝘯𝘚𝘵𝘰𝘳𝘢𝘨𝘦, 𝘯𝘢𝘷𝘪𝘨𝘢𝘵𝘰𝘳 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘦𝘳𝘳𝘰𝘳 (𝘤𝘰𝘯𝘴𝘰𝘭𝘦 𝘪𝘴 𝘵𝘩e 𝘈𝘗𝘐, 𝘦𝘳𝘳𝘰𝘳() 𝘪𝘴 𝘵𝘩𝘦 𝘮𝘦𝘵𝘩𝘰𝘥), 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘥𝘪𝘳 𝘧𝘴, 𝘱𝘳𝘰𝘤𝘦𝘴𝘴, 𝘩𝘵𝘵𝘱, 𝘦𝘵𝘤. #JavaScript #WebDevelopment #EventLoop #SoftwareEngineering
To view or add a comment, sign in
-
Why do some functions return another function(s) if we can just call the function whenever we need it? At first this feels unnecessary. If a function can already run when we call it, why would we want that function to return another function instead of just executing the logic immediately? The reason is that sometimes we want to create a function that remembers certain information for later use. Instead of passing the same data again and again every time we call a function, we can create a function that already remembers that data and uses it whenever it runs. So in some cases we are not just executing a function — we are creating a new function that carries some context with it. This behavior leads us to an important concept in JavaScript called Closures. A closure happens when a function remembers variables from the scope where it was created, even after that outer function has finished executing. Normally, when a function finishes running, its local variables should disappear. But if another function still references them, JavaScript keeps those variables alive. Closures are widely used in JavaScript for things like: • Creating private variables • Preserving state between function calls • Avoiding unnecessary global variables • Remembering configuration values • Supporting callbacks and asynchronous code In the example attached below, you can see how a function is able to access a variable that technically belongs to an outer scope. This happens because of lexical scoping, where a function remembers the environment in which it was created. Closures might seem like a small concept, but they explain many important patterns in JavaScript. A function in JavaScript doesn’t just carry its code. It also carries the environment where it was created. #javascript #closures #chaicode #chaiaurcode
To view or add a comment, sign in
-
-
If JavaScript is single‑threaded, how does it still handle Promises, API calls, and Timers without blocking the application? The answer lies in the Event Loop. Let’s take a simple example: What would be the output of the below code? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Some may guess the output to be: Start End Timeout Promise But the actual output is: Start End Promise Timeout So what is happening behind the scenes? 🔵 Synchronous Code Being synchronous, console.log("Start") and console.log("End") run immediately in the Call Stack. 🔵 Promises Resolved promises go to the Microtask Queue which is executed next. 🔵 setTimeout Timer callbacks go to the Macrotask Queue, even if the delay is '0ms', which is executed last. ✅ Simple flow to remember Synchronous Code → Promises (Microtasks) → setTimeout (Macrotasks) So even with 0 delay, Promises will always execute before setTimeout. Understanding this small but important detail will help developers debug async behavior and write more predictable JavaScript applications. #javascript #webdevelopment #eventloop #asyncprogramming
To view or add a comment, sign in
-
Most people think functions "forget" everything once they finish running. Closures change the rules! While revising JavaScript fundamentals today, closures finally made sense to me. Normally, variables are garbage collected after execution. But closures allow inner functions to access outer variables even after the outer function has finished. In simple words, the inner function “remembers” its outer scope. 💬 Why this matters: • Private Variables : Closures let us protect data by keeping variables inaccessible from outside. • Persistent State : They allow functions to remember values without relying on global variables. • Event Handlers : They help UI elements remember what action to perform later. • Modules : They help organize code and prevent naming conflicts in larger applications. What’s one JavaScript concept that recently clicked for you? 👇 #JavaScript #WebDevelopment #Closures #LearningJourney
To view or add a comment, sign in
-
-
🚀 JavaScript Magic: Why "Undefined" is actually a Feature, not a Bug! I just had a "Wow" moment diving into the JavaScript Execution Context, and it changed how I look at my code. Ever wondered why you can console.log a variable before you even declare it, and JavaScript doesn't lose its mind? 🤯 🧠 The Secret: Two-Phase Execution When your code runs, JavaScript doesn't just start at line 1. It takes two passes: 1.Memory Creation Phase: JS scans your code and allocates space for all variables and functions. 2. Execution Phase: It runs the code line-by-line. ⚡ The var Behavior (Hoisting) If you use var, JavaScript initializes it as undefined during the memory phase. Result: You can log it early. No error, just a quiet undefined. It’s like the variable is there, but its "suit" hasn't arrived yet. 🛑 The let & const Twist (TDZ) Try the same thing with let or const, and the engine throws a ReferenceError. Why? The Temporal Dead Zone (TDZ). While let and const are also "hoisted," they aren't initialized. They stay in a "dead zone" from the start of the block until the moment the code actually hits the declaration. The Lesson: JavaScript isn't just reading your code; it's preparing for it. Understanding the Execution Context makes debugging feel like having X-ray vision. 🦸♂️ Have you ever been bitten by the Temporal Dead Zone, or do you still find yourself reaching for var out of habit? Let’s discuss! 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #Programming101
To view or add a comment, sign in
-
🧠Mastering JavaScript — One Concept at a Time (2/32) Today I am very happy because my understanding of hoisting, scope, and sharing with you is now complete. 🔥Scope in Real Life Scope simply means: Where can I access this variable? Block Scope → Code inside {} like in loops, if , etc. Function Scope → Code inside a function let and const follow block scope. var ignores block scope — which leads to bugs. 🧨Hoisting JavaScript prepares memory before running code. It moves all declarations to the top — this is called hoisting. But: var is hoisted and set to undefined let and const are hoisted but not initialised — so accessing them early gives ReferenceError ⚠Common Confusions (JS Reality Checks) const doesn't make things fully constant. It protects the variable, not the value. var is outdated — it's better to use let and const let and const behave similarly, but const gives more safety use it when you're not planning to reassign. 🧠 Mindset Rule Use const by default. Use let only when you plan to change the value. Avoid var — it belongs to the past. Revisiting these fundamentals makes JavaScript feel less “magical” and more predictable. In the next post, I’ll go deeper into how the Data Type and Type System. How long did it take you to understand scope and hoisting truly? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
🚀 A JavaScript forEach() Mistake At first glance, this looks correct: const numbers = [1, 2, 3, 4]; const result = numbers.forEach(num => num * 2); console.log(result); Expected: [2, 4, 6, 8] Actual output: undefined Why? Because forEach() does not return a new array. It only executes a function for each element. So result becomes undefined. If you want to transform data, use map(). ✅ Correct approach: const numbers = [1, 2, 3, 4]; const result = numbers.map(num => num * 2); console.log(result); Now the output is: [2, 4, 6, 8] Small difference in method. Big difference in behavior. In JavaScript, choosing the right array method matters more than the logic itself. What array method confused you the most when you started? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (Microtasks vs Macrotasks) Consider this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What’s the output? Many expect: Start Timeout Promise End But actual output is: Start End Promise Timeout Why? Because of the Event Loop. JavaScript handles tasks in two major queues: • Microtasks (Promises, queueMicrotask) • Macrotasks (setTimeout, setInterval) Execution order: 1️⃣ Synchronous code runs first 2️⃣ Microtasks run next 3️⃣ Then Macrotasks Even if setTimeout has 0ms delay, it still waits for the macrotask queue. Understanding this explains: • Why some async bugs feel “random” • Why Promises run before setTimeout • Why UI updates sometimes behave unexpectedly JavaScript isn’t single-threaded chaos. It’s single-threaded with a well-defined event model. Understanding the Event Loop changes how you debug async code. What async behavior confused you the most before learning this? #javascript #frontenddeveloper #webdevelopment #eventloop #softwareengineering
To view or add a comment, sign in
-
-
Why JavaScript doesn't crash when you call a function before defining it. 🧠 I recently dove deep into the "Execution Context" of JavaScript, and the concept of Hoisting finally clicked. If you’ve ever wondered why this code works: greet(); function greet() { console.log("Hello LinkedIn!"); } ...the answer lies in how the JS Engine treats your code before it even runs a single line. The Two-Phase Secret: Memory Creation Phase: Before the "Thread of Execution" starts, JavaScript scans your code and allocates memory for variables and functions. Functions are stored in their entirety in the Variable Environment. Variables (var) are stored as undefined. Code Execution Phase: Now, the engine runs the code line-by-line. Because the function is already sitting in the memory component, calling it on line 1 is no problem! The Key Takeaway: Hoisting isn't "moving code to the top" (that’s a common myth). It’s actually the result of the Memory Creation Phase setting aside space for your declarations before execution starts. Understanding the "how" behind the "what" makes debugging so much easier. #JavaScript #WebDevelopment #CodingTips #Hoisting #ProgrammingConcepts
To view or add a comment, sign in
-
-
🚀 A Subtle JavaScript Array Bug This looks harmless: const arr = [1, 2, 3]; const copy = arr; copy.push(4); console.log(arr); Output? [1, 2, 3, 4] Why did the original array change? Because arrays (like objects) are reference types in JavaScript. copy is not a new array. It points to the same memory location. This can create unexpected side effects in larger applications. ✅ Better approach: const arr = [1, 2, 3]; const copy = [...arr]; copy.push(4); console.log(arr); // [1, 2, 3] Now you’re working with a new reference. In JavaScript, copying data is not always copying values. Sometimes it’s copying references. Understanding this saves hours of debugging. What JS concept took you the longest to truly understand? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
To view or add a comment, sign in
-
Explore related topics
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