How do i consol.log countRight with this code?

Viewed 40
function rightAnswer() {
  console.log('right')
  var countRight = 0;
  [Button2, Buttonb3].forEach(a =>
    a.addEventListener('click', () => {
      countRight += 1;

    })
  );
}

I need help with being able to print consol.log(countRight). So far when i use that line of code the consol always shows countRight = 0 even though it should say either 1 or 2 depending on the users input. I need help with making this code work.

It does not work if i put consol.log(countRight) after countRight += 1;

2 Answers

function rightAnswer() {
  var countRight = 0;
  [Button2, Buttonb3].forEach(a =>
    a.addEventListener('click', () => {
      countRight += 1;
      // this is where you should be able to log the value
      console.log(`right value is: ${countRight}`);

    })
  );
}

This is spaghetti code though. Your function breaks scope by referencing "Button2", "Buttonb3"

If you want to log on clicks the right place to log is in the click handler.

The implication from naming is that countRight will be called to increment the count–as it is no handlers will be added until countRight has been called (and it should be called only once so multiple handlers aren't added).

It might make more sense to add the handlers on the load event. If you really mean to add them at an arbitrary time in the future it can certainly be put in a method, noting again it should only be called once, or the event listeners removed before calling it again.

window.addEventListener('load', () => {
  let countRight = 0

  const button1 = document.getElementById('button1')
  const button2 = document.getElementById('button2')
  const buttons = [button1, button2]

  const output = document.getElementById('output')

  buttons.forEach(b => {
    b.addEventListener('click', b => {
      countRight++
      output.innerText = countRight
      console.log(`countRight = ${countRight}`)
    })
  })
}, false);
<button id="button1">Button #1</button>
<button id="button2">Button #2</button>
<div>Clicked <span id="output">0</span> times.</div>


Tangential

The reason to post a complete example is so people can copy it into their answers and actually run it. It also makes sense to

Related