Exercise 3: Template String: User Greeting
Problem Statement
Create a function `greet(name, city)` that returns a sentence with trimmed name/city:
`Hi <name>! Welcome to <city>.`
Note: Use `Guest` if name/city is blank.
Sample Output:
greet(" Alice ", "Mumbai") => "Hi Alice! Welcome to Mumbai."
greet(null, "") => "Hi Guest! Welcome to Guest."Solution
const clean = (s) => (String(s ?? '').trim() || 'Guest');
const greet = (name, city) => `Hi ${clean(name)}! Welcome to ${clean(city)}.`;Explanation
Overall Goal:
- User se name aur city input lena.
- Extra spaces trim karna, empty ho to "Guest" use karna.
- Template string se formatted greeting return karna.
Line 1: Helper function `clean`
const clean = (s) => (String(s ?? '').trim() || 'Guest');String(s ?? '')→ nullish coalescing operator??use karke:- Agar
snull ya undefined hai → empty string''use karo. - Agar
salready string hai → wahi use karo. String()constructor se guarantee karte hain ki result string hi hoga..trim()→ string ke start aur end se spaces remove karta hai." John "→"John"" "→""(empty string)|| 'Guest'→ logical OR operator:- Agar trimmed string empty hai (
''is falsy) →'Guest'return. - Agar trimmed string non-empty hai → wahi return.
Line 2: Main `greet` function
const greet = (name, city) =>Hi ${clean(name)}! Welcome to ${clean(city)}.;- Template string (backticks
`) use kiya hai. ${clean(name)}→ expression interpolation:clean(name)ko call karke result string me embed.${clean(city)}→ same for city.- Example:
greet(" Alice ", "Mumbai")→"Hi Alice! Welcome to Mumbai." - Example:
greet(null, "")→"Hi Guest! Welcome to Guest."
Real world:
- User registration forms me name/city fields ko clean karna zaroori hai.
- Welcome messages, email templates, dashboard greetings me ye pattern use hota hai.