Home > other >  What is the reason for returning undefined voluntarily?
What is the reason for returning undefined voluntarily?

Time:02-08

Why would you want to return undefined? for example in this discord.js code example

client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;

const { commandName } = interaction;

if (commandName === 'ping') {
    await interaction.reply('Pong!');
} else if (commandName === 'server') {
    await interaction.reply('Server info.');
} else if (commandName === 'user') {
    await interaction.reply('User info.');
}
});

Isn't returning undefined usually a sign something is wrong? So why would I return undefined voluntarily? Any clearer examples would be greatly appreciated.

CodePudding user response:

This isn't about returning undefined, the return statement is simply a guard clause. Guard clauses serve the main purpose to exit a function if certain criteria aren't met.

In this case, the reason for the guard clause is to only allow command interactions to go through, and to simply ignore button or selectmenu interactions.

  •  Tags:  
  • Related