csb00
csb00

Reputation: 1155

Returning the highest value of an array after inputting 5 numbers

I am creating an array by imputing 5 different scores. Now, I am suppose to return the highest score from that particular array. However, after I am done imputting my last score, I am getting the following message: "Highest score: undefined"

Can someone point out as to why this is occuring and help me out? I am currently learning JS.

var arrScores = [];     //I created an empty array where my scores will be stored.                            

//Here I am creating a loop so that the user can input 5 scores
for (var i = 0; i < 5; i++) {             
  arrScores.push(prompt('Please enter your score ' + (i+1))); 
}
//I created a function thinking I would be able to pull the largest score. 
function highestScore(arr){
    highestScore = Math.max(arrScores)
}
//This is suppose to be the final alert with the highest score. 
alert('Highest score: ' + highestScore.join);     

Upvotes: 2

Views: 52

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

There are couple of small mistakes in the code.

  1. highestScore is a function, you have to call the function like highestScore(<parameter>)
  2. You need to spread the array in Math.max
  3. Add the return statement in the highestScore function.
  4. You don't need to use the join, as the function will return only the max value.

I have made few changes in the code, try the below code.

Try this.

var arrScores = [];                        
for (var i = 0; i < 5; i++) {             
  arrScores.push(prompt('Please enter your score ' + (i+1))); 
}

function highestScore(arr){
    return Math.max(...arr);
}

alert('Highest score: ' + highestScore(arrScores));

Upvotes: 2

Frustrated Programmer
Frustrated Programmer

Reputation: 341

Highest score is a function. first you will need to call it

alert('Highest score: ' + highestScore(arrScores));

And to get the value you will need to return the value from the highestScore function

function highestScore(arrScores){
    highestScore = Math.max(...arrScores)
    return highestScore
}

Shorter method

function highestScore(arrScores){
    return Math.max(...arrScores)
}

Upvotes: 0

Related Questions