is the check !lastCaretState really needed? current code does not set it to undefined/null. a comment at the declaration could note the requirement to keep it like that.