Built-in objects

To add flexibility in language, JavaScript supports a number of built-in objects. The most commonly used objects are:

  • Global
  • Date
  • Math
  • RegExp (Regular Expression)
  • Array

Implementations of these built-in objects are complex and different.

Global objects

Global objects are objects defined outside the function. Every function can access these variables because their scope is global for all.

When you do not declare a variable and assign a value to it, then it will automatically become global.

Description

When your code starts execution, functions and constants immediately become available. A global variable does not initialize with the new keyword. Basically, global objects are used to share same data to add properties. You can store methods within global objects in your script.

Objects that you cannot access directly for accessing those object we use global objects. We pass those object directly as arguments after declaring the global variable. You can create a number of instances and a number of global objects in your script.

A global object has a fixed number of properties. Multiple object instances can access this global object. Here is an example:

varstudentName="Ali"
functionmyStd(){   }

student=new Global("name");
student.age=18;
person=new Global("name");
post(person.age);

Date object

Date objects in JavaScript deal with date and time objects. For example, if we are writing a script and we need some functionality of date and time, then we can use this built-in object simply.

getTime()

This function is used to get the current time with respect to the number of milliseconds since January 1, 1970.

Parameters

There are no parameters passed.

Returns

The number of milliseconds since January 1, 1970.

Description

As the name states, this function is used to obtain the current time, in the form of milliseconds. We need to create a date object first.

var time = new Date();
time.getTime(); // This will output time as 1454905019871

getMilliseconds()

This function is used to get the current time with respect to the number of milliseconds.

Parameters

There are no parameters passed.

Returns

A number from 0-999.

Description

As the name states, this function is used to obtain the current time, in the form of milliseconds. We need to create a date object first.

var time = new Date();
time.getMilliseconds();

getMinutes()

This function is used to get the current time with respect to the number of minutes.

Parameters

There are no parameters passed.

Returns

A number from 0-59.

Description

This function is used to obtain the current time, in the form of minutes. We need to create a date object first.

var time = new Date();
time.getMinutes();

getHours()

This function is used to get the current time with respect to the number of hours.

Parameters

There are no parameters passed.

Returns

A number from 0-23 with 0 being midnight.

Description

This function is used to obtain the current time, in the form of hours. We need to create a date object first.

var time = new Date();
time.getHours();

getDate()

This function is used to get the current day.

Parameters

There are no parameters passed.

Returns

A number from 1-31.

Description

This function is used to obtain the current day. We need to create a date object first.

var time = new Date();
time.getDate();

getDay()

This function is used to get the current day in the week.

Parameters

There are no parameters passed.

Returns

A number from 0-6 with 0 being Sunday.

Description

This function is used to obtain the current day in the week. We need to create a date object first.

var time = new Date();
time.getDay();

getMonth()

This function is used to get the current month.

Parameters

There are no parameters passed.

Returns

A number from 0-11.

Description

This function is used to obtain the current month in the year. We need to create a date object first.

var time = new Date();
time.getMonth();

getFullYear()

This function is used to get the current year.

Parameters

There are no parameters passed.

Returns

The year in the YYYY format.

Description

This function is used to obtain the current year. We need to create a date object first.

var time = new Date();
time.getYear();

Set date methods

Methods are available in date objects to manipulate dates. We can also adjust the date dynamically. Here is an example:

var dob=new date();
dob.setDate(19.03.1990);

We can also set upcoming dates and the current date by using this function, for example:

var dob=new date();
dob.setDate(dob.getDate + 7);

The date set methods are:

  • setTime()
  • setMilliseconds()
  • setMinutes()
  • setMinutes()
  • setHours()
  • setDate()
  • setDay()
  • setMonth()
  • setFullYear()

These methods are very similar to the date get methods described in the preceding term list.

We can also compare dates using the date object.

Math object

In JavaScript, the math object is used to perform mathematical operations.

This object has several mathematical functions. Here is an example:

  • Math.E
  • Math.PI
  • Math.sqrt
  • Math.Ln2
  • Math.ln10

The math object has different methods. For example, we have the pow method that calculates the power of the first variable times the second.

Math.pow(base, exponent);
document.write(Math.pow(2,4));  // 16 here 2 is base and 4 is exponent.

min()

This function is used to find out the the argument with the minimum value.

Parameters

The values to be evaluated are passed as parameters.

Returns

The argument with the minimum value.

Description

As the name suggests, this function is simply used to obtain the minimum value among all values in an argument

For example:

min(10, 56, 3, 26, -6, 4); //The value returned is -6

max()

This function is used to find the argument with the maximum value.

Parameters

The values to be evaluated are passed as parameters.

Returns

The argument with the maximum value.

Description

As the name suggests, this function is simply used to obtain the maximum value among all values in an argument.

For example:

max(10, 56, 3, 26, -6, 4); //The value returned is 56

random()

This function is used to generate a random number between 0 and 1.

Parameters

No parameters.

Returns

A random number between 0 and 1.

Description

The random() function is useful in generating random numbers. The value of the number will always lie between 0 and 1 (never exactly 1). For example:

Math.random();

round()

This function is used to round the number to its nearest integer value.

Parameters

The values to be evaluated are passed as parameters.

Returns

The rounded number.

Description

This method is used to create integer values after rounding them.

For example:

Math.round(4.3);// The value returned is 4
Math.round(4.8);// The value returned is 5
Math.round(4.5);// The value returned is 5

ceil()

This function is used to round a number up to the nearest and highest possible integer value.

Parameters

The values to be evaluated are passed as parameters.

Returns

The highest rounded number.

Description

This method is used to create integer values after rounding them to the higher integer.

For example:

Math.ceil(-6.2);// The value returned is -6
Math.ceil(6.2);// The value returned is 7

floor()

This function is used to round a number down to the nearest and lowest possible integer value.

Parameters

The values to be evaluated are passed as parameters.

Returns

The lowest rounded number.

Description

This method is used to create integer values after rounding them to the lower integer.

For example:

Math.floor(2.3);//The value returned is 2
Math.floor(-2.3);//The value returned is -3

The RegExp object

In JavaScript, for pattern matches in string, we use a regular expression. It is a very powerful and useful tool for expression pattern matching.

Parameters

The following are the parameters:

  • Pattern: The text/pattern of the regular expression
  • Flags: If specified, flags can have any combination of the following:
    • g: Global match
    • i: Ignore case
    • m: Multiline; treat beginning and end characters (^ and $) as working over multiple lines (that is, match the beginning or end of each line (delimited by or ), not only the very beginning or end of the whole input string)

Returns

The return type of different regular expressions is different.

Description

Using a regular expression, you can make a complex task simple by writing few lines of codes. There are five methods in JavaScript:

  • RegExp.exec(pattern)
  • RegExp.replace(pattern)
  • RegExp.split(pattern)
  • RegExp.match(pattern)

Defining a regular expression

There are two ways of writing a regular expression in JavaScript. These are:

  • RegExp constructor method
  • Literal syntax

Note

There are differences between the RegExp object and global object. They look the same but act differently.

RegExp constructor

This method is used to dynamically construct a string search pattern. A regular expression in this method should be written in quotation marks. This method has three parameters. Here is an example:

var email=new RegExp("d{2},"g");

In this example:

  • E-mail is a required parameter to which regular expression values are assigned
  • d is a pattern parameter used to match regular expression
  • g is global, which is a flag parameter. In this function, there are four types of parameters (g, I, m ,u).

Literal syntax

In literal notation, we write a regular expression without brackets. Here, i is a flag that shows to ignore case of the text whether it is uppercase, lowercase or any other. We have more flag objects such as the following ones:

  • g: Global object
  • i: Ignore case
  • m: Multi search
  • u: Unicode search

In regular expressions, we can have a global regular expression object, which will have information for each match case. A simple regular expression object has information about a particular regular expression:

var exp=d{2}/i

String object

There are four string methods for pattern matching. In these objects, a pattern is sent with a parameter. These methods allow you to search, match, replace, and split patterns.

These methods are represented as follows.

Match(pattern)

This method is used to find a matching pattern within a string. Using the not (!) operator it can also be used to find non-matches.

The syntax is string.Match(Expression).

Parameters

The string pattern that is to be matched.

Returns

It returns the result if a match is found or 0 or null if no match is found.

Description

This runs a search for matching strings in a regular expression. If the search is matched or successful then it will return an array of matching results, if not then it will return null or 0. It is also used to update properties in a regular expression.

Here is an example:

var str=("I have 10 dollars");
//The pattern below is used to find non-digits in a string
var parsestring= str.match(/D/g);

// Outputs I, ,h,a,v,e, , ,D,o,l,l,a,r,s

Replace(pattern)

This method is used to replace a part of the string.

The syntax is string.replace(stringSearched, stringReplacement).

Parameters

The string pattern that is to be replaced is passed as a parameter.

Returns

The string with the replaced value.

Description

This executes a search and is used for replacement of regular expression match resulted with alternative text. This is also used for replacement of regular expressions with specific and different regExp properties.

Here is an example:

var str1=("Apple Pie");
var parsestring1=str1.replace("Pie", "Cinnamon Roll");

Here the value of parsestring1 is Apple Cinnamon Roll.

Note

Remember here that the search is case sensitive, so if you provide the value parsestring1=str1.replace("piE", "Cinnamon Roll"); then no replacement is done.

Also, only the first occurrence of the pattern is replaced. Hence:

var str1=("Apple Pie , Banana Pie", "Strawberry PIE");
var parsestring1=str1.replace("Pie", "Cinnamon Roll");

Here the value of parsestring1 is Apple Cinnamon Roll, Banana Pie, Strawberry PIE.

To perform a global search and replacement so that all occurrences are replaced we use the following code:

var str1=("Apple Pie , Banana Pie", "Strawberry PIE");
var parsestring1=str1.replace(/Pie/g, "Cinnamon Roll");

Here the value of parsestring1 is Apple Cinnamon Roll, Banana Cinnamon Roll, Strawberry PIE.

For a global insensitive search, use the following code:

var str1=("Apple Pie , Banana Pie, "Strawberry PIE");
var parsestring1=str1.replace(/Pie/gi, "Cinnamon Roll");

Here the value of parsestring1 is Apple Cinnamon Roll, Banana Cinnamon Roll, Strawberry Cinnamon Roll.

Split(pattern)

This is use to split a string in a regular expression.

The syntax is string.split(separator,limit).

Parameters

A separator and limit are provided as optional parameters.

Returns

The split string is returned.

Description

With this method the string is split. Every word in the string is treated as a single element in an array. If a null string is passed as a parameter, the method causes each letter to be split into different characters. For example:

var str1 = "My Car is at the garage in Queens";
var parseString = str1.split("");

The value of parseString will be:

M,y, ,C,a,r, ,i,s, ,a,t, ,t,h,e, ,g,a,r,a,g,e, ,i,n, ,Q,u,e,e,n,s

Providing a limit will return a comma separated array of the words containing only the specified number of elements. For example:

var str1 = "My Car is at the garage in Queens";
var parseString = str1.split(" ", 3);

The value of parseString is My,Car,is.

Using a letter or letters as a separator will give the following results:

var str1 = "My Car is at the garage in Queens";
var parseString = str1.split("a");

The value of parseString will be:

My C,r is ,t the g,r,ge in Queens

Here is another example:

var str1 = "My Car is at the garage in Queens";
var parseString = str1.split("ar");

The value of parseString will be:

My C, is at the g,age in Queens

search(pattern)

This method is used to search for a particular string.

The syntax is string.search(stringSearched).

Parameters

The string pattern that is to be searched is passed as a parameter.

Returns

It returns the position of the starting letter of the string if a match is found. If no match is found then it returns -1.

Description

It is used to find a match in a string. If a match is found it will send an index of that match otherwise, if a match is not found, it will return -1. Global flags are not supported by this method.

Here is an example:

var str1=("I have 10 dollars in my pocket");
var parsestring=str1.search("i");

The value of parseString here is 18.

Note

There are additional string methods available to perform other tasks on strings.

A detailed list of these methods can be found at https://msdn.microsoft.com/en-us/library/ecczf11c(v=vs.94).aspx.

Array objects

An array is a collection of objects.

To create an array in JavaScript, the elements of the collection are enclosed within square brackets and separated by commas, as seen here:

varcolors = ["red", "yellow", "blue"]

An array can also be initialized using the new keyword or by specifying their length between 0 and 232-1:

new array(first, second, third, … )
new array(7)    // creates an array of size 7

To access array elements, we can use an index notation:

varlastColor = colors[2];    // blue

Always remember that array elements always start with the zero index. Hence, the third element in the preceding array has the index of 2.

Array objects can hold all sorts of data, for example, strings, numbers, literals, dates, and even user-defined objects.

.Pop()

This method is used to pop an element out of an array.

Parameters

There are no parameters for this method.

Returns

It returns the popped element of the array.

Description

Here an array is considered as a stack and the elements that are last in the array are popped out first. This follows the LIFO principle.

Here is an example:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var element= sweets.Pop();

The value of the element here is Black Forest.

.Push()

This method is used to push an element into an array.

Parameters

There are no parameters for this method.

Returns

It returns the new length of the array.

Description

Here an array is considered as a stack and the elements that are pushed appear at the end of the array.

Here is an example:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var element= sweets.Push("Lemon Meringue");

The value of the element here is 6.

.ToString()

This converts the elements in an array into a string. The elements appear as comma-separated strings.

Parameters

There are no parameters.

Returns

This returns a string containing the elements of the array.

Description

The ToString() function is used to convert an array into a string. The elements of the array appear in the string and are separated by a comma:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.ToString()

Here the value of StrSweets is:

Red Velvet,Chocolate Mousse,Strawberry Delight,Pineapple Sundae,Black Forest

.ValueOf()

This method is also used to convert an array into a string.

Parameters

There are no parameters.

Returns

This returns a string containing the elements of the array.

Description

This is default behaviour of the array and works same as the ToString() function.

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.ValueOf()

Here the value of StrSweets is:

Red Velvet,Chocolate Mousse,Strawberry Delight,Pineapple Sundae,Black Forest

.Join()

This method is used to convert an array into a string. The elements are separated by the delimiter specified.

Parameters

A separator to separate the elements in the new string.

Returns

This returns a string containing the elements of the array separated by the delimiter specified.

Description

The Join() function is used to convert an array into a string. The elements of the array appear in the string and are separated by the delimter:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.Join(*)

Here the value of StrSweets is:

Red Velvet * Chocolate Mousse * Strawberry Delight * Pineapple Sundae * Black Forest

.Splice()

Splice, as the name suggests, is used to add new elements into the array. Unlike the push() method we can add elements in whichever position we want.

Parameters

The following are the parameters:

  • Position
  • Number of elements to be removed
  • Elements to be added

Returns

The array as a string along with the new elements, if any.

Description

This method is used to remove and add elements in one step. We can specify where the new element is to be added and which elements are to be removed.

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.splice(2, 0, "Lemon Meringue");

Here the value of StrSweets is:

Red Velvet,Chocolate Mousse,Lemon Meringue,Strawberry Delight,Pineapple Sundae,Black Forest

.sort()

This method is used to sort an array into alphabetical order.

Parameters

No parameters.

Returns

The sorted array is returned.

Description

The sort method is used to sort an array, alphabetically.

Here is an example:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.Sort();

Here the value of StrSweets is:

Black Forest,Chocolate Mousse,Pineapple Sundae,Red Velvet,Strawberry Delight

.reverse()

As the name suggests it reverses the order of the array.

Parameters

No parameters.

Returns

The reversed array is returned.

Description

The reverse method is used to sort an array, alphabetically, in reverse order.

Here is an example:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.reverse();

Here the value of StrSweets is:

Strawberry Delight,Red Velvet,Pineapple Sundae,Chocolate Mousse,Black Forest.slice()

.slice()

As the name suggests, this method is used to slice up an array and create a new array using a part of the original array.

Parameters

The index at which we want the array sliced. The index of an array begins at 0. So the first element has index 0, the second element has index 1, and so on.

Returns

The sliced array containing the remaining elements is returned.

Description

The slice method is used to slice up an array and get the remainder of the array as a string.

Here is an example:

var sweets = ["Red Velvet", "Chocolate Mousse", "Strawberry Delight", "Pineapple Sundae", "Black Forest"];
var StrSweets= sweets.slice(3);

Here the value of StrSweets is:

Pineapple Sundae,Black Forest

.concat()

This method is used to concatenate two or more arrays into a single array.

Parameters

The array to be concated is passed as the parameter.

Returns

This method returns the concated array.

Description

The Concat() method is used to create a single array by joining two or more arrays.

Here is an example:

var greenShades= ["Mint", "Basil", "Pine", "Emerald"];
var BlueShades=["Azure", "Cerulean", "Navy", "Aegan"];
var VioletShades= ["Lilac", "Orchid", "Mauve", "Wisteria"];
var CoolShades=greenShades.concat(BlueShades, VioletShades);

Here the value of CoolShades is:

Mint,Basil,Pine,Emerald,Azure,Cerulean,Navy,Aegan,Lilac,Orchid,Mauve,Wisteria
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.72.176