Wednesday, December 18, 2013

JavaScript Tutorial 5 - Math

In JavaScript there are several math functions, they vary in diffifculty starting from very simple addition to some complex generating numbers. The very simple stuff looks like this syntax wise...

var add = 7 + 9
var subtract = 10 - 5
var divide = 10/2
var multiply = 5 * 5
var x = 5
var y = 7
x > y = false
x<y = true

This is as simple as it gets math wise. Now we will move on to generating numbers between 0 and 1. To do this we will use a Math random statement which looks like this...

var num = Math.random()

var num = 0.983782646377272

The number it spits out can be anywhere from 0 to 1. Now if we wanted to to make this out of a hundred for convenience, then all you would do is multiply this by 100 like so...

var num = Math.random() * 100

var num = 98.3782646377272

Now we are getting somewhere but do we really want that whole number with a ton of digits? well this is where the math round code comes in handy and it works just like this....

var num = Math.random() * 100

var round = Math.round(num)

var round = 98

Now we have a application that will spit out a random number between 1 and 100. Now how can this be used in an application? well I will show you a possible situation for its use...


var num = Math.random() * 100
var round = Math.round(num)
if (round >= 50)
{
 alert(" im smaller then 50")
}
else 
{
alert(" im greater then 50")
}

This is just a simple app that will trigger an alert statement based of the number generated. This is the basic concept of math in JavaScript.




No comments:

Post a Comment