Javascript var variable not working as global

I have a variable declared as counts before the add_to_download_entries() function and I am using it later in the $(document).ready( function () { function but it always print the value 1 of count however when I tested the value of count changes depending on how many checboxes are selected in the add_to_download_entries but it’s not reflected the same value outside that function in the $(document).ready( function (). Am I using the variables wrong?

Close
Pay Now $

var selected_lostwill_array = [];

var counts = 1;
var checkboxes;

function add_to_download_entries(data) {
  checkboxes = document.querySelectorAll('input[name="checkWills"]:checked');
  counts = checkboxes.length;
  if ($.inArray(data, selected_lostwill_array) >= 0) {
    selected_lostwill_array = $.grep(selected_lostwill_array, function(value) {
      return value != data;
    });
  } else {
    selected_lostwill_array.push(data);
  }
}
// DataTables Functions 
$(document).ready(function() {
  $('#org_lost_table').DataTable();
  $('#all_lost_table').DataTable();
  if (counts > 0) {
    let finalPrice = Number(counts) * Number(22);
    $("#payment-sub-btn").append(counts);
  } else $("#payment-sub-btn").append(0);
});
<td>
  <input type="checkbox" name="checkWills" onclick='add_to_download_entries("{{$will->id}}")' />&nbsp;
</td>