skip to Main Content

Imagine I have a function looks like this:

const greetings = name => {
   return name === undefined ? 'Hello!' : `Hello, ${name || 'user'}!`;
}

There’re two ways to call this function:

  1. greetings()

  2. greetings(user.name)

For the first use case, because it is called explicitly without an argument, I just want it to output "Hello". Which is working as intended.

For the second use case, if the user.name is "Bob", it should output "Hello, Bob!". But if the user doesn’t have a name (user.name is undefined). It should fallback to "user": "Hello, user!", but now it outputs "Hello!".

I know I could change the function to (...args) => {} or change it to function greetings() {} and use arguments. But I’m just curious, is there a way to distinguish these two use cases without changing the function declaration?

const greetings = name => {
   return name === undefined ? 'Hello!' : `Hello, ${name || 'user'}!`;
}

const user1 = { id: 1, name: 'Bob' };
const user2 = { id: 2 };  // The user hasn't set up completely

console.log(greetings());             // Hello!
console.log(greetings(user1.name));   // Hello, Bob!
console.log(greetings(user2.name));   // Hello, user!

2

Answers


  1. You can use the null for this case. For eg:

    console.log(greetings(null)); // Hello, user!

    So, you need to call the greetings like greetings(userName || null)

    const greetings = name => {
       return name === undefined ? 'Hello!' : `Hello, ${name || 'user'}!`;
    }
    
    let name;
    console.log(greetings(name));       // Hello!
    console.log(greetings()); // Hello!
    name = 'Bob'; 
    console.log(greetings(name)); // Hello, Bob!
    name = undefined;
    console.log(greetings(name || null));   // Hello, user!
    Login or Signup to reply.
  2. "Without changing function body?" no.

    But here is a more elegant way using optional chaining

    const greetings = user => `Hello${ user ? `, ${user?.name ?? 'user'}` : ''}!`;
    
    const user1 = { id: 1, name: 'Bob' };
    const user2 = { id: 2 }; // The user hasn't set up completely
    
    console.log(greetings());      // Hello!
    console.log(greetings(user1)); // Hello, Bob!
    console.log(greetings(user2)); // Hello, user!

    Or if you want to keep the greetings function simple

    const greetings = (name = '') => `Hello${name}!`;
    const getName = user => user ? `, ${user?.name ?? 'user'}` : ''
    
    const user1 = { id: 1, name: 'Bob' };
    const user2 = { id: 2 }; // The user hasn't set up completely
    
    
    console.log(greetings());      // Hello!
    console.log(greetings(getName(user1))); // Hello, Bob!
    console.log(greetings(getName(user2))); // Hello, user!
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search