🚀 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
JavaScript Web APIs Explained
More Relevant Posts
-
"How did adopting HTML-first frameworks like HTMX and Astro decrease our development time by 47%? Let's dive into the details. Do you believe in the power of progressive enhancement to redefine web application development? In my latest project, I shifted from a traditional JavaScript-heavy approach to embracing HTML-first frameworks. This shift isn't just about cutting down on JavaScript; it's about prioritizing user experience and accessibility. By building the core functionality in HTML and using HTMX to sprinkle interactivity, our team's bug rate dropped significantly. We lean into progressive enhancement, ensuring users with limited JavaScript capabilities still experience a functional site. Astro further streamlined this process, allowing us to deliver lightning-fast static sites with a reactive user experience when needed. In practice, this meant focusing first on HTML for the core page structure, then layering interactivity as needed. Here's a quick HTMX snippet that transformed our data fetching process: ```typescript import { fetchFromAPI } from './api'; document.querySelector('#my-button').addEventListener('click', async () => { const data = await fetchFromAPI('/endpoint'); document.querySelector('#output').textContent = data.result; }); ``` Using 'vibe coding' allowed us to prototype these enhancements rapidly, testing different levels of interactivity before full implementation. It challenged us to rethink our development workflow, prioritizing robust performance over feature bloat. How would you incorporate progressive enhancement in your current projects? Would you consider giving HTML-first frameworks a try? Let's hear your thoughts!" #WebDevelopment #TypeScript #Frontend #JavaScript
To view or add a comment, sign in
-
🚀 ECMAScript 2025 — Not just another update. Some features actually change how we write JavaScript. Instead of listing everything, here are the ones that actually matter with real examples 👇 --- 👉 1. Iterator Helpers (Better Performance) Before (creates multiple arrays): const result = [1,2,3,4] .filter(x => x > 2) .map(x => x * 2); Now (lazy execution, no extra arrays): const result = [1,2,3,4] .values() .filter(x => x > 2) .map(x => x * 2) .toArray(); ✔ Cleaner ✔ Faster for large datasets --- 👉 2. New Set Methods (Finally useful Sets) const a = new Set([1,2,3]); const b = new Set([2,3,4]); console.log(a.union(b)); // {1,2,3,4} console.log(a.intersection(b)); // {2,3} console.log(a.difference(b)); // {1} console.log(a.symmetricDifference(b));// {1,4} ✔ No more manual loops ✔ Much cleaner logic --- 👉 3. JSON Modules (Direct Import) import config from './config.json' with { type: 'json' }; console.log(config.apiUrl); ✔ No extra parsing ✔ Cleaner configs --- 👉 4. Promise.try() (Cleaner Error Handling) Promise.try(() => riskyFunction()) .then(res => console.log(res)) .catch(err => console.error(err)); --- 💡 My Take: Most JS updates are incremental. But features like Iterator Helpers & Set methods actually improve how we think about data handling. If you're ignoring these, you're just writing older JS in a newer environment. --- #JavaScript #WebDevelopment #Frontend #NodeJS #Programming #ECMAScript
To view or add a comment, sign in
-
localStorage vs sessionStorage in JavaScript frontend Both are used to store data in the browser, but choosing the right one is important for application behavior localStorage Data persists even after closing the browser Shared across all tabs of the same origin Best suited for long term data like user preferences sessionStorage Data exists only for the duration of the tab session Cleared when the tab is closed Isolated per tab Best suited for temporary data like session state Key difference comes down to data lifecycle and scope localStorage for persistence sessionStorage for session based isolation Using the wrong storage can lead to unexpected user experience issues Frontend decisions are not just UI level They directly impact how users interact with your application #javascript #frontend #performance
To view or add a comment, sign in
-
Smart Pivot Table from https://htmlelements.com is highlighted as a high-performance solution for large datasets in this comparative analysis of JavaScript tools. The component is recognized for its intuitive API, placing it alongside other industry leaders in the JavaScript landscape. Read the full article on DEV Community - https://lnkd.in/dqhcaCYq
To view or add a comment, sign in
-
Smart Pivot Table from https://htmlelements.com is highlighted as a high-performance solution for large datasets in this comparative analysis of JavaScript tools. The component is recognized for its intuitive API, placing it alongside other industry leaders in the JavaScript landscape. Read the full article on DEV Community - https://lnkd.in/diGN4727
To view or add a comment, sign in
-
Many developers confuse slice() and splice() in JavaScript. The difference is simple but important. 1️⃣ slice() — Creates a copy slice() returns a portion of an array without changing the original array. Example: const numbers = [10, 20, 30, 40, 50] const result = numbers.slice(1, 4) Result → [20, 30, 40] Original → [10, 20, 30, 40, 50] Use it when you want to extract data safely without modifying the source array. 2️⃣ splice() - Modifies the array splice() changes the original array. It can remove, add, or replace elements. Example 1 - Remove items: const numbers = [10, 20, 30, 40, 50] numbers.splice(2, 2) Result → [10, 20, 50] It removed 30 and 40 from the original array. Example 2 - Add Items : constnumbers= [10, 20, 50]; numbers.splice(2, 0, 30, 40); console.log(numbers); // [10, 20, 30, 40, 50] Explanation: It Start at index 2, Remove 0 items and Insert 30 and 40 Key Difference slice() → non-destructive (does not modify the array) splice() → destructive (modifies the array) Quick rule to remember slice → copy splice → change Understanding this small difference prevents many bugs, especially when working with React state and immutable data patterns. #javascript #webdevelopment #frontend #reactjs #programming
To view or add a comment, sign in
-
🚨 JavaScript “this” Trap — Arrow Function vs Regular Function const counter = { value: 42, show: () => this.value, }; console.log(counter.show.call({ value: 100 })); // undefined ❗ 💡 What’s happening? Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (usually the global scope). So even when we try to override this using .call(), .apply(), or .bind(), it doesn’t work. 👉 That’s why the result is undefined instead of 100. ✅ When to use Arrow Functions: • When you want to preserve the outer this (e.g., inside callbacks, closures) • In React functional components or array methods (map, filter, etc.) • When you don’t need dynamic context ❌ When NOT to use Arrow Functions: • Object methods that rely on this • Constructors (they can’t be used with new) • Event handlers where this refers to the element • When you need .call(), .apply(), or .bind() 🔥 Fix the issue: const counter = { value: 42, show() { return this.value; }, }; console.log(counter.show.call({ value: 100 })); // 100 ✅ ⚡ Key Takeaway: Arrow functions are not a replacement for regular functions — they’re a different tool. Use them wisely. Misusing them can silently break your logic. #JavaScript #WebDevelopment #Frontend #MERN #CodingTips #CleanCode #reactjs #nodejs
To view or add a comment, sign in
-
-
🧠 Day 27 — Set & Map in JavaScript (Simplified) JavaScript gives you more than just arrays & objects — meet Set and Map 🚀 --- ⚡ 1. Set 👉 A collection of unique values const set = new Set([1, 2, 2, 3]); console.log(set); // {1, 2, 3} --- 🔧 Common Methods set.add(4); set.has(2); // true set.delete(1); 👉 Perfect for removing duplicates --- ⚡ 2. Map 👉 Stores key-value pairs (like objects, but better in some cases) const map = new Map(); map.set("name", "John"); map.set(1, "Number key"); console.log(map.get("name")); // John --- 🧠 Why Map over Object? ✔ Keys can be any type (not just strings) ✔ Maintains insertion order ✔ Better performance in some cases --- 🚀 Why it matters ✔ Cleaner data handling ✔ Useful in real-world apps ✔ Avoid common object limitations --- 💡 One-line takeaway: 👉 “Set handles unique values, Map handles flexible key-value pairs.” --- Once you start using these, your data handling becomes much more powerful. #JavaScript #Set #Map #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🔑 JavaScript Set Methods – Quick Guide 1. Creation const letters = new Set(["a","b","c"]); // from array const letters = new Set(); // empty letters.add("a"); // add values 2. Core Methods MethodPurposeExampleReturns add(value)Add unique valueletters.add("d")Updated Set delete(value)Remove valueletters.delete("a")Boolean clear()Remove all valuesletters.clear()Empty Set has(value)Check existenceletters.has("b")true/false sizeCount elementsletters.sizeNumber 3. Iteration Methods MethodPurposeExample forEach(callback)Run function for each valueletters.forEach(v => console.log(v)) values()Iterator of valuesfor (const v of letters.values()) {} keys()Same as values() (compatibility with Maps)letters.keys() entries()Iterator of [value, value] pairsletters.entries() 4. Key Notes Unique values only → duplicates ignored. Insertion order preserved. typeof set → "object". set instanceof Set → true. 📝 Exercise Answer Which method checks if a Set contains a specified value? 👉 Correct answer: has() 🎯 Memory Hooks Set = Unique Collection Think: “No duplicates, only distinct members.” add to insert, has to check, delete to remove, clear to reset.
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗢𝗳 𝗦𝗶𝗻𝗴𝗹𝗲-𝗧𝗵𝗿𝗲𝗮𝗱𝗲𝗱 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You use JavaScript to build web applications. But do you know how it works? JavaScript is a single-threaded language. This means it executes one operation at a time on a single thread. Here's what you need to know: - JavaScript is single-threaded, but it can still handle asynchronous operations - It uses the event loop, callback queues, and asynchronous APIs to achieve non-blocking behavior - The event loop manages the execution of code, events, and messages in a non-blocking manner The event loop works like this: - JavaScript pushes the execution context of functions onto the call stack - When it encounters asynchronous operations, it delegates them to Web APIs or Node APIs - The event loop monitors the call stack and callback queue, pushing callbacks onto the call stack for execution You can see this in action with a simple example: ``` is not allowed, so here is the example in plain text: console.log("Start") setTimeout(() => { console.log("End") } This is how it works: - The first console.log("Start") is executed - The setTimeout() function is encountered and placed in the call stack - After 2 seconds, the callback function is moved to the callback queue - The event loop checks if the call stack is empty, then pushes the callback function onto the call stack for execution Source: https://lnkd.in/gtPp3Cvy
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