Why do we need async/await in JavaScript? Async/await is a major source of confusion in JavaScript. People tend just to add and remove the async and await keywords until the code works (or seems to work). In this article, I want to explain what async/await actually means by developing the concept from vanilla, synchronous JavaScript to asynchronous JavaScript with the async/await syntax sugar. It is my personal take on the subject. I hope some will find it interesting. Disclaimer: I use Node.js as an example of a JavaScript runtime in this article. However, what's discussed also applies to other runtimes like web browser JS engines. All these environments follow similar architectures. Suppose you have a function that does some I/O. function handleRequest() { try { const data = doDatabaseQuery(); const fileName = doElasticsearchQuery(data); const result = readMyFile(fileName); return result; } catch (err) { return handleError(err); } } Here we assume that the query functions and the readMyFile functio https://lnkd.in/gkSCJnHx
Understanding Async/Await in JavaScript
More Relevant Posts
-
Mastering JavaScript's URL() and URLSearchParams: A Complete Guide Introduction Working with URLs in JavaScript used to be a messy affair involving string manipulation, regular expressions, and brittle parsing logic. The modern URL() and URLSearchParams APIs changed everything, providing robust, standardized interfaces for URL manipulation that solve countless headaches developers face daily. In this comprehensive guide, we'll explore these APIs in depth, understanding not just how they work, but why they exist and the specific problems they solve. The URL() constructor creates URL objects that represent and parse Uniform Resource Locators. It takes a URL string (and optionally a base URL) and returns an object with properties representing each component of the URL. new URL(url) new URL(url, base) Parameters: url (required): An absolute or relative URL string base (optional): A base URL string to resolve relative URLs against When you create a URL object, it automatically parses the URL into its constituent parts: const url = new URL('https://john: https://lnkd.in/guUd-Kp4
To view or add a comment, sign in
-
Mastering JavaScript's URL() and URLSearchParams: A Complete Guide Introduction Working with URLs in JavaScript used to be a messy affair involving string manipulation, regular expressions, and brittle parsing logic. The modern URL() and URLSearchParams APIs changed everything, providing robust, standardized interfaces for URL manipulation that solve countless headaches developers face daily. In this comprehensive guide, we'll explore these APIs in depth, understanding not just how they work, but why they exist and the specific problems they solve. The URL() constructor creates URL objects that represent and parse Uniform Resource Locators. It takes a URL string (and optionally a base URL) and returns an object with properties representing each component of the URL. new URL(url) new URL(url, base) Parameters: url (required): An absolute or relative URL string base (optional): A base URL string to resolve relative URLs against When you create a URL object, it automatically parses the URL into its constituent parts: const url = new URL('https://john: https://lnkd.in/guUd-Kp4
To view or add a comment, sign in
-
🔥 Day 14 — Async JavaScript, Web APIs & the Event Loop JavaScript is a synchronous, single-threaded language — one call stack, one task at a time. Yet it still handles timers, network calls, UI events, and heavy async tasks smoothly. How? 👇 🌐 The Browser Superpowers The JS engine lives inside the browser, and the browser provides powerful Web APIs like: setTimeout() fetch() localStorage console These are not part of JavaScript. They come from the browser environment, and JS uses them to perform async tasks. ⚙️ The Event Loop Magic When you call setTimeout or fetch: Timer callbacks go to the Callback Queue Promise .then() callbacks go to the Microtask Queue The Event Loop acts like a gatekeeper: it checks whether the call stack is empty and pushes tasks from the queues. 🔥 Microtask Queue > Callback Queue The Microtask Queue (promises, mutation observers) has higher priority. If it keeps getting new tasks, the Callback Queue must keep waiting. This situation is called: 👉 Microtask Queue Starvation (Callback queue never gets a chance to run because microtasks keep filling up.) 🧠 Why This Matters Understanding queues, event loop behavior, and task priorities is what separates a regular JS coder from someone who truly understands the runtime.
To view or add a comment, sign in
-
-
💡 Do you know the shortest program in JavaScript? Yes — it’s an empty file! Even if there’s literally nothing in your JS file, the JavaScript engine still does important work behind the scenes. Here’s why: 1️⃣ Global Execution Context is Created JS first sets up a Global Execution Context (GEC). This is the space where global variables live, functions are defined, and the global object is connected. 2️⃣ Global Object is Initialized Browser: window → contains console, document, alert, setTimeout… Node.js: global → contains process, Buffer, require, setTimeout… This object is the foundation for all code, even if the file is empty. 3️⃣ this Refers to the Global Object Inside the global context: Browser → this === window Node → this === global Example: console.log(this); // window (browser) or [Object: global] (Node) 4️⃣ No Code = No Execution, But Environment Exists The engine checks for statements to run. If the file is empty, nothing executes — but all the setup has already happened. ✅ Takeaway: The program is syntactically valid (no errors) It’s functionally empty (nothing runs) Global environment is initialized (GEC, global object, this)
To view or add a comment, sign in
-
-
What is JSX and how is it converted into JavaScript? JSX: Syntax extension for JavaScript, mainly used with React. HTML in JS: Allows writing HTML-like code inside JavaScript for easier readability and maintenance. Expressions: Embed JavaScript expressions in JSX using {}. Example of JSX: The name written in curly braces { } signifies JSX const name = "Learner"; const element = ( <h1> Hello, {name}.Welcome to Rajshahi . </h1> ); Browsers can’t understand JSX directly. Instead, tools like Babel transpile it into plain JavaScript using React.createElement(). const element = <h1>Hello, Rajshahi!</h1>; Babel converts it into: const element = React.createElement("h1", null, "Hello, World!");
To view or add a comment, sign in
-
🌟 Day 10: Introduction to Asynchronous JavaScript 🚀 “JavaScript doesn’t wait… it multitasks!” 🔹 Synchronous vs Asynchronous JavaScript 🧩 Synchronous JS → Executes line by line, one task at a time. 🌀 Asynchronous JS → Can perform multiple tasks without waiting for one to finish. --- ⚡ Example: console.log("1️⃣ Start"); setTimeout(() => { console.log("2️⃣ Async Task (after 2s)"); }, 2000); console.log("3️⃣ End"); 🧠 Output: 1️⃣ Start 3️⃣ End 2️⃣ Async Task (after 2s) 👉 Even though the timeout is written second, it executes later because it’s asynchronous. --- 💡 Why it matters? Asynchronous JavaScript makes web apps fast, responsive, and user-friendly — essential for tasks like: Fetching data from APIs Handling user events Running background operations
To view or add a comment, sign in
-
-
🔄 JavaScript Type Conversion — Turning One Type Into Another! 😎 In JavaScript, Type Conversion means changing a value from one data type to another — for example, from a string to a number, or from a number to a string. There are two main types of conversions you should know 👇 --- ⚙️ 1. Implicit Conversion (Type Coercion) JavaScript does this automatically when needed. Example: console.log("5" + 2); // "52" → number turns into string console.log("5" - 2); // 3 → string turns into number 🧠 JS tries to “help” you by converting types automatically — but sometimes this can cause surprises! 😅 --- ⚙️ 2. Explicit Conversion (Manual Conversion) You do it yourself using functions or methods. Examples: Number("10"); // Converts string to number → 10 String(20); // Converts number to string → "20" Boolean(0); // Converts number to boolean → false ✅ More reliable because you control when and how it happens. --- 💬 Quick Tip: Use typeof to check what type your value currently is 👇 typeof "Hello" // "string" typeof 42 // "number" --- 💡 In Short: Type conversion helps your program stay flexible and smart — but always be aware of how JavaScript converts things behind the scenes! #JavaScript #CodingTips #WebDevelopment #JSBeginners #LearnJS #Frontend
To view or add a comment, sign in
-
-
Mastering JavaScript map(): Hidden Pitfalls and Smarter Patterns JavaScript’s Array.prototype.map() is simple on the surface yet surprisingly deep once you inspect how callbacks, types, coercion, and encoding work under the hood. One of the most infamous examples — [1,2,3].map(parseInt) — looks harmless but produces confusing output that often appears in interviews. This guide breaks everything down clearly: how map() really works, why parseInt misbehaves, how NaN is detected, how wrapper objects make "text".length possible, and why emoji “length” is unintuitive. Each section includes modern examples and best-practice patterns. map() Actually Works 1.1 Syntax and Basic Behavior map() creates a brand-new array using your callback’s return values. The original array is never modified. const transformed = sourceList.map( (itemValue, itemPosition, originalList) => { return /* computed value */; }, optionalThisArgument ); const baseNumbers = [2, 5, 10]; const doubledValues = baseNumbers.map(num => num * 2); console.log(doubledValu https://lnkd.in/gbec6TSU
To view or add a comment, sign in
-
Mastering JavaScript map(): Hidden Pitfalls and Smarter Patterns JavaScript’s Array.prototype.map() is simple on the surface yet surprisingly deep once you inspect how callbacks, types, coercion, and encoding work under the hood. One of the most infamous examples — [1,2,3].map(parseInt) — looks harmless but produces confusing output that often appears in interviews. This guide breaks everything down clearly: how map() really works, why parseInt misbehaves, how NaN is detected, how wrapper objects make "text".length possible, and why emoji “length” is unintuitive. Each section includes modern examples and best-practice patterns. map() Actually Works 1.1 Syntax and Basic Behavior map() creates a brand-new array using your callback’s return values. The original array is never modified. const transformed = sourceList.map( (itemValue, itemPosition, originalList) => { return /* computed value */; }, optionalThisArgument ); const baseNumbers = [2, 5, 10]; const doubledValues = baseNumbers.map(num => num * 2); console.log(doubledValu https://lnkd.in/gbec6TSU
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