Categories
JavaScript

JavaScript number functions and operations

Examples of mixing numbers and strings:

  • “1” + 2 + 4 will evaluate to 124 (looks like if the compiler finds a string the rest will also be considered a string)
  • 2 + 5 + “8” will evaluate to 78 (looks like after the compiler finds a string, then it behaves as one, but not before)
  • Number(“1”) + 2 + 4 will evaluate to 7
  • Instead of Number(), you can use +, like: +”1″ + 2 + 4

Parsing numbers:

  • parseInt(“3F”,16); Convert 3F hexadecimal to int. If you use 10 it will be decimal instead
  • parseInt will look for numbers at the beginning of the string, as oppose to Number, which will return NAN if a string is assigned to it
  • parseFloat parses floats

Other number functions:

  • isNaN(x)) Checks if x is a number. Returns true or false accordingly.
  • Math.round(number) Rounds the number to its closes integer.
  • Math.ceiling(x) Produce the ceiling of a number.
  • Math.floor(x) Produce the floor of a number
  • Useful function to produce random numbers from 1 to 9: Math.floor(Math.random()*10);
    This is a more generic representation of it:
    number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)
    If you want to select
    a number between 2 and 10, then the code would look like this:
    var num = Math.floor(Math.random() * 9 + 2);

Categories
JavaScript

JavaScript boolean operators

&&, || and !

Also, when comparing boolean variables, negative numbers, 0, NaN, and empty strings will produce false, everything else will be taken as boolean true.

If you want to avoid typecasting when testing variables, use ===

Categories
JavaScript

JavaScript data types

Number, String, Boolean, Function, Object, Null, Undefined.

All Variables in javascript are object types.

Creating a function:

var square = new Function (“x”,”return x*x”);

The difference between null and undefined is that null is declared but has no value, and undefined has never been declared

Categories
JavaScript

Detect operative system with JavaScript

navigator.appVersion