Two very simple operations that you may have to deal with if writing a JavaScript that deals with trigonometry are Math.degrees() and Math.radians(). These function can be easily defined as follows:


// Converts from degrees to radians.
Math.radians = function(degrees) {
  return degrees * Math.PI / 180;
};

// Converts from radians to degrees.
Math.degrees = function(radians) {
  return radians * 180 / Math.PI;
};

The name of these functions indicates the end result. Using the above definitions, you could run code such as the following to get the results indicated in the comments:


alert(Math.radians(90));  // 1.5707963267948966
alert(Math.radians(180)); // 3.141592653589793

alert(Math.degrees(1.5707963267948966)); // 90
alert(Math.degrees(3.141592653589793));  // 180

These two functions are now available in YourJS:

I figured if it is available in a language like Python, it might as well be available in the best scripting language, JavaScript!!! 😎


7 Comments

Javier Roman · May 24, 2014 at 3:29 PM

I thought I had this down, but I had the ratio multipliers flipped. Thanks for clarifying this so simply! I bookmarked ya.

idk · June 25, 2014 at 4:29 AM

maybe,

Math.prototype.radians = function(degrees) {}

?

Les · September 1, 2015 at 5:46 PM

Thanks for that, not the math but so obvious thing like adding it to the Math object once, then use forever 🙂

Tori · April 18, 2016 at 6:00 AM

Thank you for clarifying this for me. Everywhere else I looked made it sound so complicated and confusing.

Noitidart · April 23, 2016 at 6:45 AM

Very useful. I am making a html5 drawing application so was drawing triangles and arrows and other shapes. This came in handy! Thank you!

Frank · June 8, 2016 at 12:55 PM

This helped me out with something I was working on… thank you!

Jacob · October 23, 2018 at 7:49 PM

This turned out to be much simpler than expected.
Thank you!

Leave a Reply to Les Cancel reply

Your email address will not be published. Required fields are marked *