Search code examples
javascriptarraysstringintegerconsole.log

why is my console displaying my result as numbers insteadof the actual string in my array in the code below


var arrayNames = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];

function whosPaying(names) {
  var bigBoss = arrayNames.length;
  var ogaMi = Math.floor((Math.random() * bigBoss));

  return ogaMi + " is paying for the bill"
}

console.log(whosPaying());


Solution

  • The reason is you just get the index,not the element itself

    so change

     var ogaMi = Math.floor((Math.random() * bigBoss));
    

    to

     var ogaMi = arrayNames[Math.floor((Math.random() * bigBoss))];
    

    var arrayNames = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];
    
    function whosPaying(names) {
      var bigBoss = arrayNames.length;
      var ogaMi = arrayNames[Math.floor((Math.random() * bigBoss))];
    
      return ogaMi + " is paying for the bill"
    }
    
    console.log(whosPaying());