Creating multiple unique random strings from single array in Discord.js bot

I’m working on a Discord bot and having trouble generating different random alphanumeric strings each time. Right now when someone uses the !generate command, I want to create several unique strings but they keep coming out the same.

Here’s my current setup:

const Discord = require('discord.js');
const settings = require('./settings.json');

module.exports = {
    name: 'generate',
    description: 'Creates random alphanumeric codes',
    
    run(msg) {
        if (msg.channel.id !== settings.codeChannel) {
            const wrongChannelEmbed = new Discord.MessageEmbed()
                .setColor('#ff0000')
                .setTitle('Incorrect Channel')
                .setDescription(`Please use <#${settings.codeChannel}> for code generation`)
                .setAuthor(msg.author.username, msg.author.avatarURL())
                .setTimestamp();
            return msg.channel.send(wrongChannelEmbed);
        }
        
        const randomCode = Math.random().toString(36).substring(2) + '\n';
        
        const resultEmbed = new Discord.MessageEmbed()
            .setColor('#00ff00')
            .setTitle('Generated Codes')
            .setDescription(`${randomCode}${randomCode}`)
            .setAuthor(msg.author.username, msg.author.avatarURL())
            .setTimestamp();
            
        msg.channel.send(resultEmbed);
    }
};

The problem is that when I try to display multiple codes by repeating the variable, they show up identical instead of being different random strings. How can I make each one unique?

You’re storing the random string in a variable once, then reusing that same value everywhere. JavaScript only runs Math.random().toString(36).substring(2) when you first assign it to randomCode - not every time you use the variable. You need to generate a fresh random string for each code. Either call the random generation separately each time, or wrap the Math.random logic in a function and call it multiple times. That’ll fix it.

hey, i think i see your issue! you’re generating the randomCode only once, so it ends up being the same when you try to use it again. try calling Math.random().toString(36).substring(2) each time you want a new code instead of saving it to a variable.