Skip to content Skip to sidebar Skip to footer

Simplifying/Combining If Statement Logic (When Using Numbers)

I have been looking around, googling here and there, how to properly code a very simplistic calculator. More specifically a Boolean calculator with set values. If I've lost you, be

Solution 1:

First, try to make code as reusable as possible. So,

if (a.checked) {
  console.log('Arg True')
  i = i + 80;
  d.value = i;
} else {
  console.log('Arg False')
  d.value = i;
}

if (b.checked) {
  console.log('Arg True')
  i2 = i2 + 30;
  e.value = i2
} else {
  console.log('Arg False')
  e.value = i2;
}

can be replaced as

function dummy(el, val) {
  i2 += el.checked ? val : 0;
}

Second, do not have inline functions in HTML. It will dirty your HTML and make debug difficult. You should wrap all listeners in a wrapper function. This will enable you to even export all of them to separate file and you will know where to look.

Third, instead of hard coding value 80 or 30 in your code, make a map or bind it to element using data-attribute

Fourth and more Important one, use better variable names. a-e or i, i1, i2 are bad names. Only you will understand your code (till you are in context). Always use precise meaningful name. This will help in long run. I have even kept function names as long as 30+ chars just to define its purpose.

Also try to break your code in smaller functions. This will increase scope for reusing them.

You can refer updated code and ask any queries, if you have.

Hope it helps!


Post a Comment for "Simplifying/Combining If Statement Logic (When Using Numbers)"