0
function markAnswer(i){
  poll.selectedAnswer = +i;
  try {
    document.querySelector(".poll .answers .answer.selected").classList.remove("selected");
  } catch(msg){}
  document.querySelectorAll(".poll .answers .answer")[+i].classList.add("selected");
  showResults();
}

I understand what [i] mean in array. However, I don't understand what does [+i] mean. I can assume that [+i] is related to array, but I don't know why there is + sign in front of i.

And this code is from YouTube channel called CodingFlag. I watched CodingFlag and found out this code and I try to read and learn something from it, but I can't understand that [+i] part.

phuzi
  • 12,078
  • 3
  • 26
  • 50
MINN
  • 1
  • `+i` casts the content of `i` into a number – Andreas Jul 01 '21 at 09:35
  • 1
    `+i` converts `i` to a number. It should be completely useless here, because there are no actual numeric indexes in JS - all keys are converted to a string, so `arr[1]` actually addresses the `"1"` key. In some circumstances, there is special treatment for keys that represent non-negative integers, e.g., `"0"`, `"1"`, `"2"`, but again - they are still strings. Doesn't matter whether you use `foo[1]` or `foo["1"]` to access those. – VLAZ Jul 01 '21 at 09:36

0 Answers0