# JavaScript Powered Ratio Calculator

*JavaScript can make your life easier.*

# I see your math challenge and ratio a calculator (pun intended)

I recently created a new tool for a friend which essentially helps calculate a value based on a ratio. For example, if the chosen ratio is 16:9, if *a* is = 1920, then *b* = 1080. Essentially, if you populate the *a* field, the calculator will give you the value of *b* and vice versa.

The JavaScript code I used is perhaps crude, but effective. It was a fun experiment playing with parts of JavaScript I seldom touched (such as vanilla JS Event handlers, and Event Targets), due to my prior affinity for jQuery.

## Working Calculator to play with

*To see the fully working JavaScript code for the calculator, jump down to the bottom of this article.*

## The science behind the calculator

There are essentially 4 variables at play in the calculation formula:

`((a:b) === (y:x))`

If we were to calculate a modern HD computer screen pixel height based on width alone, we'd set the first 3 variables as follows:

`a = 16`

, `b=9`

,`y=1920`

To calculate the value of `x`

, we can perform the below simple formula:

`x = y / (a / b)`

Using this formula, and based on the above variable values, the value of `x`

will become 1080, thus completing the calculation, informing us that 1920 x 1080 is equivalent to a 16:9 ratio.

#### Reversing the calculator...

Say we already know the value of `x`

, but want to know the value of `y`

instead. We just reverse the calculation:

`y = (a / b) * x`

## Full working code for the calculator

Please note, that I built the calculator using plain JavaScript code, and it is 100% jQuery free.

Optimising the small things in life, for developers and people.