Does it matter when we use the preventDefault method? (right in the beginning of a function vs at the end). All the tutorials that I have watched place preventDefault at the end of the function, but I would assume the first thing you want to do is prevent the default behavior. I have noticed that it works if it's at the beginning of the function and it works at the very end of the function:
function calculateResults(e){
e.preventDefault();
//UI Vars
const amount = document.querySelector(`#amount`);
const interest = document.querySelector(`#interest`);
const years = document.querySelector(`#years`);
const monthlyPayment = document.querySelector(`#monthly-payment`);
const totalPayment = document.querySelector(`#total-payment`);
const totalInterest =document.querySelector(`#total-interest`);
const princapal = parseFloat(amount.value);
const calculatedInterest = parseFloat(interest.value)/100/12;
const calculatedPayment = parseFloat(years.value) * 12;
// compute monthly payments
const x = Math.pow(1 + calculatedInterest, calculatedPayment);
}
VS
function calculateResults(e){
//UI Vars
const amount = document.querySelector(`#amount`);
const interest = document.querySelector(`#interest`);
const years = document.querySelector(`#years`);
const monthlyPayment = document.querySelector(`#monthly-payment`);
const totalPayment = document.querySelector(`#total-payment`);
const totalInterest =document.querySelector(`#total-interest`);
const princapal = parseFloat(amount.value);
const calculatedInterest = parseFloat(interest.value)/100/12;
const calculatedPayment = parseFloat(years.value) * 12;
// compute monthly payments
const x = Math.pow(1 + calculatedInterest, calculatedPayment);
e.preventDefault();
}
I guess my main concern is if I have a lot going on in the function is it possible that the browser will do its default behavior before it gets to preventDefault at the end? Or will it wait to do everything in the function before it attempts to do its default behavior?
The best practice is to call it as soon as possible.
If any error is thrown within the code before it reaches the preventDefault
it may not get called and browser will perform the default action.
Once it is called however if an error is thrown after that the default action won't occur