Sending personalised messages to user using JavaScript

We need to write a JavaScript function that sends personalized messages based on whether the user is the owner or a regular user. The function takes two parameters: the user name and the owner name.

Problem Statement

Create a function that compares the user name with the owner name and returns appropriate greetings:

  • If the user is the owner: return "Hello master"
  • If the user is different from owner: return "Hello" followed by the user's name

Solution

Here's the implementation using a simple conditional statement:

const name = 'arnav';
const owner = 'vijay';

function greet(name, owner) {
    if (name === owner) {
        return 'Hello master';
    }
    return `Hello ${name}`;
}

console.log(greet(name, owner));
Hello arnav

Example with Owner Access

Let's see what happens when the user is the owner:

const userName = 'vijay';
const ownerName = 'vijay';

function greet(name, owner) {
    if (name === owner) {
        return 'Hello master';
    }
    return `Hello ${name}`;
}

console.log(greet(userName, ownerName));
Hello master

Enhanced Version with Multiple Users

Here's a more practical example testing multiple users:

function personalizedGreeting(userName, ownerName) {
    return userName === ownerName ? 'Hello master' : `Hello ${userName}`;
}

const owner = 'admin';
const users = ['john', 'admin', 'sarah', 'mike'];

users.forEach(user => {
    console.log(`User: ${user} -> ${personalizedGreeting(user, owner)}`);
});
User: john -> Hello john
User: admin -> Hello master
User: sarah -> Hello sarah
User: mike -> Hello mike

Key Points

  • Use strict equality (===) to compare strings accurately
  • Template literals (`${}`) provide clean string interpolation
  • Ternary operator offers a concise alternative for simple conditions
  • The function handles both owner and regular user scenarios effectively

Conclusion

This personalized greeting function demonstrates basic conditional logic in JavaScript. It's useful for creating user-specific interfaces where owners receive special treatment while regular users get personalized messages.

Updated on: 2026-03-15T23:19:00+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements