I'm practicing javascript, and I have this DoodleJump-like program. The point is that I want a list of highscores to be displayed on screen when the game is over, but it doesn't work. It throws me a TypeError just like this...
Uncaught TypeError: Cannot set property 'innerHTML' of null
at showHighScores (app.js:246)
at checkHighScore (app.js:236)
at gameOver (app.js:208)
at app.js:115
Here's some code:
Function supposed to display highscores...
function showHighScores() {
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? [];
const highScoreList = document.getElementById(highScores);
console.log(highScores)
highScoreList.innerHTML = highScores
.map((score) => `<li>${score.score} - ${score.name}`)
.join('');
}
Function supposed to Check that a highscore is a highscore.
function checkHighScore(){
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? [];
const lowestScore = highScores[NO_OF_HIGH_SCORES - 1]?.score ?? 0;
if (score > lowestScore) {
saveHighScore(score, highScores); // TODO
showHighScores(); // TODO
}
}
To save the highscores on the browser's storage...
function saveHighScore(score, highScores) {
const name = prompt('You got a highscore! Enter name:');
const newScore = { score, name };
// 1. Add to list
highScores.push(newScore);
// 2. Sort the list
highScores.sort((a, b) => b.score - a.score);
// 3. Select new list
highScores.splice(NO_OF_HIGH_SCORES);
// 4. Save to local storage
localStorage.setItem(HIGH_SCORES, JSON.stringify(highScores));
};
The strange thing is that I did a console.log displaying the highScores variable (which according to the program is null) and a set of my present and previous scores is displayed, so, I'm quite confused.
I will vote up the person who helps me out with this one. I appreaciate it in advance.