Get random number with JavaScript

In PHP the rand() function returns a random number between a given minimum and maximum (by default 0 and 32767). The whole looks like this:

<?php
  $randomNumber = rand(1,100); // random number between 1 and 100
  echo $randomNumber;
?>

The same function can be rebuild with JavaScript:

<script type="text/javascript">
  function rand(min,max){
    if (arguments.length === 0){
      min = 0;
      max = 32767;
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
 
  var randomNumber = rand(1,100); // random number between 1 and 100
  document.write(randomNumber);
</script>

How to parse JSON with jQuery

With jQuery you could easily parse a JSON (which is an object in JavaScript Object Notation). The method parseJSON of jQuery translates the JSON even into the corresponding JavaScript data types. As an example I have chosen the following JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
        "firstName": "Joe",
        "lastName" : "Black",
        "age"      : 28,
        "address"  :
        {
          "streetAddress": "1st Street",
          "city"         : "New York",
          "state"        : "NY",
          "postalCode"   : "10021"
        },
        "phoneNumber":
        [
          {
            "type"  : "home",
            "number": "212555-1234"
          },
          {
            "type"  : "fax",
            "number": "646555-4567"
          }
        ],
        "married" : true,
        "developer" : true	
}

This JSON contains nested objects like address, an array like phoneNumber and key-value pairs of different types like firstName (string), age (number) and married (boolean).

Here it is shown how it is parsed:
How to parse JSON with jQuery weiterlesen

How to check for NaN with JavaScript?

If you explicitly convert a JavaScript variable to a number (e.g. by using the parseInt function), then you have to check if the value of the converted number is really a number. In case that it is not, it will present you NaN (Not a Number). You can check for NaN with the isFinite function.

Example:

1
2
3
4
5
6
// Check for hexadecimal value
var convertedNumber = parseInt('G', 16);
if(isFinite(convertedNumber) == false)
  alert('The value of the converted number is NaN!');
else
  alert('The number is: '+convertedNumber);