Sunday, 21 August 2016

JavaScript Math and Date Object

The Math object
It is used to perform arithmetic operations.

Properties of Math object
Properties
Description
E
Holds Euler’s number whose approximate value is 2.718
LN2
Holds natural logarithm of 2, whose approximate value is 0.693
LN10
Holds natural logarithm of 10, whose approximate value is 2.302
LOG2E
Holds the base-2 logarithm of E, whose approximate value is 1.442
LOG10E
Holds the base-10 logarithm of E, whose approximate value is 0.434
PI                
Holds the numeric value of PI, whose approximate value is 0.707
SQRT1_2
Holds the square root of ½, whose approximate value is 0.707
SQRT2
Holds the square root of 2, whose approximate value is 1.414

Methods of the Math object
Method
Description
abs(x)
Returns the absolute value of x
acos(x)
Returns arccosine(in radian) of x
asin(x)
Returns arcsine(in radian) of x
atan(x)
Returns the arctangent of x with numeric value between –PI/2 and PI/2 radians
atan2(y,x)
Returns the arctangent of the quotation on dividing y and x
ceil(x)
Round up x to the nearest bigger integer
cos(x)
Returns cosine value of x
exp(x)
Returns the value of ex
floor(x)
Rounds up x to the nearest smaller integer
log(x)
Returns the natural logarithm value of x
max(x,y,z,…,n)
Returns the highest number from the given list
min(x,y,z,…,n)
Returns the lowest number from the given list
pow(x,y)
Returns x to the power of y
random()
Returns a random number between 0 and 1
round()
Rounds up x to the nearest integer
sin(x)
Returns sine value of x
sqrt(x)
Returns the square root of x
tan(x)
Returns the tangent value of x


 Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Math Object</title>
</head>
<body>
    <h1>JavaScript Math Object</h1>
    <script>
        document.write('Floor: ' + Math.floor(11.456) + '<br/>');
        document.write('Ceil: ' + Math.ceil(11.456) + '<br/>');
        document.write('Log: ' + Math.log(11.456) + '<br/>');
        document.write('Max: ' + Math.max(11.456,12,56,1,-78) + '<br/>');
        document.write('Min: ' + Math.min(11.456, -87, 78, 34) + '<br/>');
        document.write('Power: ' + Math.pow(14,2) + '<br/>');
        document.write('random: ' + Math.random() + '<br/>');
        document.write('round: ' + Math.round(11.456) + '<br/>');
        document.write('sin: ' + Math.sin(60) + '<br/>');
        document.write('tan: ' + Math.tan(45) + '<br/>');
        document.write('exp: ' + Math.exp(6) + '<br/>');
    </script>
</body>
</html>



The Date object
It is used to display a date on a web page or a timestamp in numerical or mathematical calculation.
The Date object can represents dates 285616 years before or after January 1, 1970.
var date1=new Date(); or var date1= new Date(milliseconds);
or var date1= new Date(yyyy, mm , dd [, hr , min, sec, millisec]); or
var date1= new Date(“mm dd, yyyy”); or var date1= new Date(“mm dd, yyyy hr:min:sec”);

Properties of the Date object

Properties
Description
constructor
Holds the value of constructor function that has created the object
prototype
Adds properties and methods to the Date object

Methods of the Date Object

Methods
Description
getDate()
Returns the day of the month that ranges from 1 to 31
getDay()
Returns the numeric equivalence of the day of a week that is 0 to 6. 0 for Monday and 6 for Sunday
getFullYear()
Returns the numerical equivalence of year in four digit
getHours()
Return the hours which ranges from 0 to 23
getMilliseconds()
Returns the milliseconds that ranges from 0 to 999
getMinutes()
Returns minutes that ranges from 0 to 59
getMonth()
Returns numerical equivalence of month that ranges from 0 to 11
getSeconds()
Returns the seconds that ranges from 0 to 59
getTime()
Returns number of milliseconds since midnight jan1,1970
getTimezoneOffset()
Returns the difference of time (in minutes) between the Greenwich mean time(GMT) and the local time
getUTCDate()
Returns the day of the month that ranges from 1 to 31 as per the universal time
getUTCDay()
Returns the numeric equivalence of the day of a week that is 0 to 6. 0 for Monday and 6 for Sunday as per the universal time
getUTCFullYear()
Returns the numerical equivalence of year in four digit as per the universal time
getUTCHours()
Return the hours which ranges from 0 to 23 as per the universal time
getUTCMilliseconds()
Returns the milliseconds that ranges from 0 to 999 as per the universal time
getUTCMinutes()
Returns minutes that ranges from 0 to 59 as per the universal time
getUTCMonth()
Returns numerical equivalence of month that ranges from 0 to 11 as per the universal time
getUTCSeconds()
Returns the seconds that ranges from 0 to 59 as per the universal time
parse()
Parses a date string and returns the number of millisecond since the midnight of January 1,1970
setDate()
Sets the day of a month that ranges from 1 to 31
setFullYear()
Sets the year in four digits
setHours()
Sets the hours that ranges from 0 to 23
setMilliseconds()
Sets the milliseconds that ranges from 0 to 999
setMinutes()
Sets the minutes that ranges from 0 to 59
setMonth()
Sets the numerical equivalence of month that ranges from 0 to 11
setSeconds()
Sets the seconds that ranges from 0 to 59
setTime()
Sets a date and time by adding or subtracting specified milliseconds to/from midnight January 1,1970
setUTCDate()
Sets the day of a month that ranges from 1 to 31 as per the universal time
setUTCFullYear()
Sets the year in four digits as per the universal time
setUTCHours()
Sets the hours that ranges from 0 to 23 as per the universal time
setUTCMilliseconds()
Sets the milliseconds that ranges from0 to 999 as per the universal time
setUTCMinutes()
Sets the minutes that ranges from 0 to 59 as per the universal time
setUTCMonth()
Sets the numerical equivalence of month that ranges from 0 to 11 as per the universal time
setUTCSeconds()
Sets the seconds that ranges from 0 to 59 as per the universal time
toDateString()
Converts date into string
toLocalDateString()
Converts date into string as per local conventions
toLocalTimeString()
Converts time into string as per local conventions
toLocalString()
Converts the date object into a string as per local convetions
toString()
Converts the date object into a string
toTimeStamp()
Converts time into a string
toUTCString()
Converts the date object into string as per the universal time
UTC()
Holds the number milliseconds since the midnight of January 1, 1970, as per the universal time
valueOf()
Returns the primitive value of the Date object.

Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Date Object</title>
</head>
<body>
    <h1>JavaScript Date Object</h1>
    <script>
        var date = new Date();
        document.write('Todays Date: ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + '<br/>');
        document.write('Time Is: ' + date.getHours() + '/' + (date.getMinutes() + 1) + '/' + date.getSeconds() + '<br/>');

    </script>
</body>
</html>



JavaScript Number and Array Object

The Number object
Numbers in JavaScript are 64 bit (8 bytes) floating point numbers.

Syntax for creating Number object
var num = new Number(value)

Properties of Number object

Properties
Description
constructor
Holds the value of constructor function that has created the object
MAX VALUE
Returns the maximum numerical value possible in javaScript
MIN VALUE
Returns the minimum numerical value possible in javaScript
NEGATIVE INFINITY
Represents the value of negative infinity
POSITIVE INFINITY
Represents the value of positive infinity
prototype
Adds properties and methods to the number object

Methods of the Number object


Method
Description
toExponential(x)
Converts number into exponential notation
toFixed(x)
Rounds up a number to x digit after the decimal
toPrecision(x)
Rounds up a number to a length of x digits
toString()
Returns a string value of the Number object
valueOf()
Returns a primitive value of the Number object

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Number Objects</title>
</head>
<body>
    <h1>JavaScript Number Objects</h1>
    <script>
        number = new Number(12.5678);
        document.write(number.toExponential() + '<br/>');
        document.write(number.toFixed() + '<br/>');
        document.write(number.toPrecision(2) + '<br/>');
        document.write(number.toString() + '<br/>');
        document.write(number.valueOf() + '<br/>');
    </script>
</body>
</html>
The Array object
It is store multiple values in a single variable. It can hold different data type value in a single slot.

It can be created using
1.       array constructor
2.       array literal notation

Using array constructor
Creating empty array: var new_array= new array();
Creating array of a given size: var new_array= new array(size);
Creating array with elements: var new_array= new array(“first element”, “second Element”);

Using array literal notation
Array literal notation is a comma separated list of items enclosed by square brackets.
Creating empty array: var new_array=[];
Creating array with elements: var new_array= [“element1”, “element2”];

Properties of array object

Properties
Description
constructor
Holds the value of constructor function that has created the object
length
Holds the number of elements in an array
prototype
Adds properties and methods to the array object

Methods of an array object

Properties
Description
concat()
Joins two or more arrays and returns the joined array
join()
Joins all the elements of an array into a string
pop()
Removes the last element of an array and return the element
push()
Adds new element as last element and returns length of the new array
reverse()
Reverses the order of list of element in an array
shift()
Removes the first element of an array and returns the element
slice()
Selects a part of an array and returns that part of new array.
sort()
Sorts the element of an array
splice()
Adds or removes the element of an array
toString()
Converts an array into a string and returns the string
unshift()
Adds new elements to an array and returns the new length
valueof()
Returns the primitive value of an array object

Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Array Objects</title>
</head>
<body>
    <h1>JavaScript Array Objects</h1>
    <script>
        array_months = new Array('Jan', 'Feb', 'Mar', 'April', 'May', 'June');
        array_num = new Array(1, 2, 3, 4, 5, 6);
        document.write('Array 1: '+array_months + '<br/>');
        document.write('Array 2: ' + array_num + '<br/>');
        document.write('concat two arrays: ' +  array_months.concat(array_num) + '<br/>');
        document.write('join two arrays: ' + array_months.join(array_num) + '<br/>');
        document.write('Array 1 pop out: ' + array_months.pop() + '<br/>');
        document.write('Array 2 revers: ' + array_num.reverse() + '<br/>');
        document.write('Shifted array 1 : ' + array_months.shift() + '<br/>');
        document.write('Sorted array 1: ' + array_months.sort() + '<br/>');
    </script>
</body>
</html>

JavaScript Boolean Object

The Boolean Object
It returns either true or false. It is wrapper class and a member of global objects. It returns false when the object is passed with values, such as 0, empty string, false, null, undefined, not a number(NaN).

It can be created in following ways
1.       Using boolean literal
2.       Using the Boolean object as function
3.       Using the testable expressions

Using Boolean literal
It uses true or false, to inherit the member of the Boolean object.
var bool=true;
document.write(bool);
document.write(bool.toString());

Using Boolean object as function
They are used to pass the value as an argument.
var bool=Boolean(false);

Using testable expressions
They are used to evaluate the output in Boolean values.
If(true)
{
}

Properties of Boolean object
Property
Description
constructor
Returns the function, which has created the prototype of the Boolean object
prototype
Allows us to add properties and methods to an object

Methods of the Boolean object

Method
Description
toString()
Converts the Boolean value into string and returns the string
valueOf()
Returns the primitive value of an Boolean object

Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Boolean Objects</title>
</head>
<body>
    <h1>JavaScript Boolean Objects</h1>
    <script>
        var bool1 = new Boolean(0);
        var bool2 = new Boolean(7);
        var bool3 = new Boolean('');
        var bool4 = new Boolean('One');
        var bool5 = new Boolean('false');
        var bool6 = new Boolean(null);
        var bool7 = new Boolean(NaN);
        document.write('0 value is :' + bool1 + '<br/>');
        document.write('5 value is :' + bool2 + '<br/>');
        document.write('empty string value is :' + bool3 + '<br/>');
        document.write('One value is :' + bool4 + '<br/>');
        document.write('false value is :' + bool5 + '<br/>');
        document.write('null value is :' + bool6 + '<br/>');
        document.write('NaN value is :' + bool7 + '<br/>');
    </script>
</body>
</html>


JavaScript Regular Expression Object

The RegExp Object
It is used to validate a pattern of characters.

How to define a regular expression
1.       Using RegExp objects constructor function.
2.       Using literal.

Using RegExp: var regularexpression = new RegExp(“pattern”,”flag”);
Using literal: /pattern/flag

Types of flags in JavaScript
1.       g- finds all matches globally
2.       i- ignores the case in searches, i.e. text written in lowercase is same as uppercase.
3.       m- represents multiline matching, i.e. the symbol caret(^) and dollar($) match the beginning  and end of the line as well as entire string.

Patterns used in the RegExp object

Pattern delimiters:
Pattern
Description
(pattern),(?:pattern)
Matches the entire contained pattern

(pattern) retains the match

(?:pattern) does not retain the match

Lookaheads
Pattern
description
(?=pattern),(?!pattern)
(?=pattern) matches only if the condition is satisfied

(?!pattern) matches only if the condition is not satisfied

Character Escapes
Pattern
Description
\f
Matches form feed
\r
Matches carriage return
\n
Matches linefeed
\t
Matches horizontal tab
\v
Matches vertical tab
\0
Matches null character
[\b]
Matches back space
\s
Matches whitespace
\S
Matches anything but a whitespace
\w
Matches any alphanumerical character including underscore
\W
Matches any non-word character
\d
Matches any digit
\D
Matches any non-digit
\b
Matches a word boundary
\B
Matches a non-word boundary
\cX
Matches a control character. Example g:\cd matches control-d
\xhh
Matches the character with two characters with hexadecimal code hh
\uhhh
Matches the Unicode character with four characters of hexadecimal code hhhh

Character Sets
Pattern
Description
[character],[^character]
[character] matches all the contained character

[^character] matches all but the contained characters

List of Quantifiers of the RegExp Object
Quantifier
Description
n+
Represents a string which contains at least one n
n*
Represents a string that contains zero or more occurrences of n
n?
Represents a string that contains zero or one occurrences of n
n{a}
Represents a string that contains n, a number of times
n{a,b}
Represents a string that contains n, a to b number of times
n{a,}
Represents a string that contains n, a or more number of times
n$
Represents a string that ends with n
^n
Represents a string that starts with a
?=n
Represents a string that is followed by specific string  n
?!n
Represents a string that is not followed by specific string n

Properties of RegExp Object
Property
Description
global
Refers that the g modifier is set
ignoreCase
Refers that the I modifier is set
lastIndex
Refers the index to start the next match
multiline
Refers that the m modifier is set
source
Refers the text of RegExp pattern


Methods of RegExp object
Method
Description
compile
Compiles the RegExp object
exec
Tests for the match in a string and returns a result array
test
Tests for a match in a string and returns true or false