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:
-
greetings()
-
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
You can use the
null
for this case. For eg:console.log(greetings(null)); // Hello, user!
So, you need to call the
greetings
likegreetings(userName || null)
"Without changing function body?" no.
But here is a more elegant way using optional chaining
Or if you want to keep the greetings function simple