Exercise 1: Toggle Password Visibility

Problem Statement

Create a function `togglePassword(inputEl, btnEl)` that toggles input type "password" ↔ "text" and updates button text.

Sample Output:

togglePassword(inputEl, btnEl)
// If inputEl.type === "password":
//   inputEl.type => "text", btnEl.textContent => "Hide"
// If inputEl.type === "text":
//   inputEl.type => "password", btnEl.textContent => "Show"

Solution

const togglePassword = (inputEl, btnEl) => {
  const isPw = inputEl.type === 'password';
  inputEl.type = isPw ? 'text' : 'password';
  btnEl.textContent = isPw ? 'Hide' : 'Show';
};

Explanation

Overall Goal:

  • Password input field ko show/hide karna.
  • Button text ko accordingly update karna.

Line 1: Function header

  • const togglePassword = (inputEl, btnEl) => {
  • inputEl → password input element.
  • btnEl → toggle button element.

Line 2: Check current state

  • const isPw = inputEl.type === 'password';
  • inputEl.type → input element ka type property.
  • === 'password' → strict equality check.
  • isPw → boolean: kya abhi password mode me hai?

Line 3: Toggle input type

  • inputEl.type = isPw ? 'text' : 'password';
  • Ternary operator:
  • Agar isPw true hai (password mode) → 'text' set (show password).
  • Agar isPw false hai (text mode) → 'password' set (hide password).

Line 4: Update button text

  • btnEl.textContent = isPw ? 'Hide' : 'Show';
  • Button text ko current state ke opposite me update:
  • Agar password mode me hai → "Hide" (kyunki ab show hoga).
  • Agar text mode me hai → "Show" (kyunki ab hide hoga).

Real world:

  • Login/signup forms: password visibility toggle.
  • Settings pages: sensitive fields show/hide.
  • User experience: password confirmation me help.