Exercise 5: Copy to Clipboard (button)

Problem Statement

Create a function `copyText(text)` that copies to clipboard. Return success/fail boolean.

Sample Output:

await copyText("Hello World") => true (if successful)
await copyText("test") => false (if clipboard API unavailable)

Solution

const copyText = async (text) => {
  try { await navigator.clipboard.writeText(String(text)); return true; }
  catch { return false; }
};

Explanation

Overall Goal:

  • Text ko clipboard me copy karna.
  • Success/failure handle karna (async operation).

Line 1: Async function

  • const copyText = async (text) => {
  • async → function async hai (Promise return karega).
  • Clipboard API async hai, isliye async zaroori.

Line 2: Try block

  • try { await navigator.clipboard.writeText(String(text)); return true; }
  • try → error handling.
  • navigator.clipboard → browser ka Clipboard API.
  • .writeText(...) → text ko clipboard me write karta hai (Promise return).
  • await → Promise resolve hone tak wait karo.
  • String(text) → text ko string me convert (safety).
  • return true → success case me true return.

Line 3: Catch block

  • catch { return false; }
  • Agar error aaya (permission denied, etc.) → catch block execute.
  • return false → failure case me false return.

Why async?

  • Clipboard API Promise-based hai (security reasons).
  • User permission required ho sakta hai.

Real world:

  • Coupon codes: "Copy Code" button.
  • Referral links: share links copy karna.
  • Code snippets: example code copy karna.