Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the reason for returning undefined voluntarily?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading