This code runs all fine, except the very last bit. The newCard function doesn't work for some reason. Please help


<p id ="message-el"><em>Want to play a round?</em></p>
<p id ="cards-el">Cards:</p>
<p id = "sum-el">Sum:</p>

<button onclick ="start()">START GAME</button>

<button onclick ="newCard()">NEW CARD</button>
let firstCard = 2;
let secondCard = 7;

let isAlive = true;
let message = "";
let messageEl = document.getElementById("message-el");
let sumEl = document.getElementById("sum-el");

let cards = document.getElementById("cards-el");

function start() {
  cards.innerHTML = "Cards: " + firstCard + " " + secondCard;
  let sum = firstCard + secondCard;
  sumEl.textContent = "Sum: " + sum;
  if (sum <= 21) {
    message = "You want another card?";
  } else if (sum == 21) {
    message = "You've got a blackjack!";
  } else {
    message = "You're out of the game!";
    isAlive = false;
  messageEl.innerHTML = message;

function newCard() {
   let card = 3;
   sum += card;

sum is undefined inside the newCard function so doing += is a reference error. Even if it was defined unless it is also initialized to a value you can’t += with a number and undefined.

If you want both functions to have access to the variable you need to declare it outside the functions (or pass it to the functions).

But I’m honestly not sure what the code is supposed to do.

Yes, it was locally scoped. Declared the sum variable in global scope. It worked now.
You are a champ, cheers!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.