1

I am writing this as a lambda function which should Display a random string out of the declared array, but upon the time of execution, it displays "NULL". Please can anyone suggest me the correct code or syntax and tell me whats wrong with this code.

exports.handler = async (event) => {
    let messages = ["AWS","Pranav","Hello World"];
    let response = messages[Math.floor(Math.random()*100)];
    return response;
};
Vlad Holubiev
  • 4,876
  • 7
  • 44
  • 59
Pranav
  • 9
  • 1

1 Answers1

0

Nothing to do with Lambda, error is in the way you take a random array element.

Change it to this:

exports.handler = async (event) => {
    let messages = ["AWS","Pranav","Hello World"];
    let response = messages[Math.floor(Math.random()*messages.length)];
    return response;
};

Instead of multiplying Math.random() by 100, which gives you a random number between 0 and 100, you should multiply it by messages.length.

More examples on generating a random number in JS here: https://stackoverflow.com/a/24152886/2727317

Vlad Holubiev
  • 4,876
  • 7
  • 44
  • 59