How does onchange and onkeyup work in javascript?

I was trying to validate a password field when I found the javascript code on the net. Can someone please explain when is the “onchange” fired and why does the code not work when I replace onkeyup with onchange (last 2 lines in javascript code)

function validatePassword(){
              if(password.value != confirm_password.value) {
                confirm_password.setCustomValidity("Passwords Don't Match");
              } else {

            password.onchange = validatePassword;
            confirm_password.onkeyup = validatePassword;
<div class="password" id="password-fields" style="display:none"> 
                Password: <input type="password" name="password" class="password" id="password"><br>
                Confirm Password: <input type="password" name="password" class="password" id="confirm-password">

            <div> <input type="submit" name="submit"> </div>



The change event occurs when you leave an input field after having changed its value. It doesn’t fire immediately as the user changes the value, only when they’ve finished, which is detected by them using the keyboard or mouse to select a different element on the page.

The keyup event occurs after every keystroke. This allows you to take action while the user is typing.