ES6 – Modules ”; Previous Next Introduction Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your rescue with the concept of Modules. A module organizes a related set of JavaScript code. A module can contain variables and functions. A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use. Variables and functions within a module should be exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode. This means variables or functions declared in a module will not be accessible globally. Exporting a Module The export keyword can be used to export components in a module. Exports in a module can be classified as follows − Named Exports Default Exports Named Exports Named exports are distinguished by their names. There can be several named exports in a module. A module can export selected components using the syntax given below − Syntax 1 //using multiple export keyword export component1 export component2 … … export componentN Syntax 2 Alternatively, components in a module can also be exported using a single export keyword with {} binding syntax as shown below − //using single export keyword export {component1,component2,….,componentN} Default Exports Modules that need to export only a single value can use default exports. There can be only one default export per module. Syntax export default component_name However, a module can have a default export and multiple named exports at the same time. Importing a Module To be able to consume a module, use the import keyword. A module can have multiple import statements. Importing Named Exports While importing named exports, the names of the corresponding components must match. Syntax import {component1,component2..componentN} from module_name However, while importing named exports, they can be renamed using the as keyword. Use the syntax given below − import {original_component_name as new_component_name } All named exports can be imported onto an object by using the asterisk * operator. import * as variable_name from module_name Importing Default Exports Unlike named exports, a default export can be imported with any name. Syntax import any_variable_name from module_name Example: Named Exports Step 1 − Create a file company1.js and add the following code − let company = “TutorialsPoint” let getCompany = function(){ return company.toUpperCase() } let setCompany = function(newValue){ company = newValue } export {company,getCompany,setCompany} Step 2 − Create a file company2.js. This file consumes components defined in the company1.js file. Use any of the following approaches to import the module. Approach 1 import {company,getCompany} from ”./company1.js” console.log(company) console.log(getCompany()) Approach 2 import {company as x, getCompany as y} from ”./company1.js” console.log(x) console.log(y()) Approach 3 import * as myCompany from ”./company1.js” console.log(myCompany.getCompany()) console.log(myCompany.company) Step 3 − Execute the modules using an HTML file To execute both the modules we need to make a html file as shown below and run this in live server. Note that we should use the attribute type=”module” in the script tag. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> <meta http-equiv=”X-UA-Compatible” content=”ie=edge”> <title>Document</title> </head> <body> <script src=”./company2.js” type=”module”></script> </body> </html> The output of the above code will be as stated below − TutorialsPoint TUTORIALSPOINT Default Export Step 1 − Create a file company1.js and add the following code − let name = ”TutorialsPoint” let company = { getName:function(){ return name }, setName:function(newName){ name = newName } } export default company Step 2 − Create a file company2.js. This file consumes the components defined in the company1.js file. import c from ”./company1.js” console.log(c.getName()) c.setName(”Google Inc”) console.log(c.getName()) Step 3 − Execute the modules using an HTML file To execute both the modules we need to make an html file as shown below and run this in live server. Note that we should use the attribute type=”module” in the script tag. <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> <meta http-equiv=”X-UA-Compatible” content=”ie=edge”> <title>Document</title> </head> <body> <script src=”./company2.js” type=”module”></script> </body> </html> The output of the above code will be as mentioned below − TutorialsPoint Google Inc Example: Combining Default and Named Exports Step 1 − Create a file company1.js and add the following code − //named export export let name = ”TutorialsPoint” let company = { getName:function(){ return name }, setName:function(newName){ name =newName } } //default export export default company Step 2 − Create a file company2.js. This file consumes the components defined in the company1.js file. Import the default export first, followed by the named exports. import c, {name} from ”./company1.js” console.log(name) console.log(c.getName()) c.setName(“Mohtashim”) console.log(c.getName()) Step 3 − Execute the modules using an HTML file <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> <meta http-equiv=”X-UA-Compatible” content=”ie=edge”> <title>Document</title> </head> <body> <script src=”company2.js” type=”module”></script> </body> </html> The output of the above code will be as shown below − TutorialsPoint TutorialsPoint Mohtashim Print Page Previous Next Advertisements ”;
Category: es6
ES6 – Error Handling
ES6 – Error Handling ”; Previous Next There are three types of errors in programming: Syntax Errors, Runtime Errors, and Logical Errors. Syntax Errors Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript. When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads get executed assuming nothing in them depends on the code containing the error. Runtime Errors Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution. Logical Errors Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result as expected. You cannot catch those errors, because it depends on your business requirement, what type of logic you want to put in your program. JavaScript throws instances of the Error object when runtime errors occur. The following table lists predefined types of the Error object. Sr.No Error Object & Description 1 EvalError Creates an instance representing an error that occurs regarding the global function eval(). 2 RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. 3 ReferenceError Creates an instance representing an error that occurs when dereferencing an invalid reference. 4 SyntaxError Creates an instance representing a syntax error that occurs while parsing the code. 5 TypeError Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. 6 URIError Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters. Throwing Exceptions An error (predefined or user defined) can be raised using the throw statement. Later these exceptions can be captured and you can take an appropriate action. Following is the syntax for the same. Syntax: Throwing a generic exception throw new Error([message]) OR throw([message]) Syntax: Throwing a specific exception throw new Error_name([message]) Exception Handling Exception handling is accomplished with a try…catch statement. When the program encounters an exception, the program will terminate in an unfriendly fashion. To safeguard against this unanticipated error, we can wrap our code in a try…catch statement. The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch Following is the syntax for the same. try { // Code to run [break;] } catch ( e ) { // Code to run if an exception occurs [break;] }[ finally { // Code that is always executed regardless of // an exception occurring }] Example var a = 100; var b = 0; try { if (b == 0 ) { throw(“Divide by zero error.”); } else { var c = a / b; } } catch( e ) { console.log(“Error: ” + e ); } Output The following output is displayed on successful execution of the above code. Error: Divide by zero error Note − Note: You can raise an exception in one function and then you can capture that exception either in the same function or in the caller function using a try…catch block. The onerror( ) Method The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page. Example <html> <head> <script type = “text/javascript”> window.onerror = function () { document.write (“An error occurred.”); } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = “button” value = “Click Me” onclick = “myFunc();” /> </form> </body> </html> Output The following output is displayed on successful execution of the above code. The onerror event handler provides three pieces of information to identify the exact nature of the error − Error message − The same message that the browser would display for the given error. URL − The file in which the error occurred. Line number − The line number in the given URL that caused the error. The following example shows how to extract this information. Example <html> <head> <script type = “text/javascript”> window.onerror = function (msg, url, line) { document.write (“Message : ” + msg ); document.write (“url : ” + url ); document.write (“Line number : ” + line ); } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = “button” value = “Click Me” onclick = “myFunc();” /> </form> </body> </html> Custom Errors JavaScript supports the concept of custom errors. The following example explains the same. Example 1: Custom Error with
ES6 – RegExp
ES6 – RegExp ”; Previous Next A regular expression is an object that describes a pattern of characters. Regular expressions are often abbreviated “regex” or “regexp”. The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on the text. A regular expression can be defined as − var pattern = new RegExp(pattern, attributes); OR var pattern = /pattern/attributes; The attribute can have any combination of the following values. Sr.No Attribute & Description 1 G Global Match 2 I Ignore case 3 M Multiline; treat the beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or the end of each line (delimited by n or r), not only the very beginning or end of the whole input string) 4 U Unicode; treat the pattern as a sequence of unicode code points 5 Y Sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes) Constructing Regular Expressions Brackets Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters. Sr.No Expression & Description 1 […] Any one character between the brackets 2 [^…] Any one character not between the brackets 3 [0-9] It matches any decimal digit from 0 through 9 4 [a-z] It matches any character from lowercase a through lowercase z 5 [A-Z] It matches any character from uppercase A through uppercase Z 6 [a-Z] It matches any character from lowercase a through uppercase Z The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v. Quantifiers The frequency or position of the bracketed character sequences and the single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence. Sr.No Expression & Description 1 p+ It matches any string containing at least one p. 2 p* It matches any string containing zero or more p”s 3 p? It matches any string containing one or more p”s 4 p{N} It matches any string containing a sequence of N p”s 5 p{2,3} It matches any string containing a sequence of two or three p”s 6 p{2, } It matches any string containing a sequence of at least two p”s 7 p$ It matches any string with p at the end of it 8 ^p It matches any string with p at the beginning of it 9 [^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z 10 p.p It matches any string containing p, followed by any character, in turn followed by another p 11 ^.{2}$ It matches any string containing exactly two characters 12 <b>(.*)</b> It matches any string enclosed within <b> and </b> 13 p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp Literal Characters Sr.No Character & Description 1 Alphanumeric Itself 2 The NULL character (u0000) 3 t Tab (u0009) 4 n Newline (u000A) 5 v Vertical tab (u000B) 6 f Form feed (u000C) 7 r Carriage return (u000D) 8 xnn The Latin character specified by the hexadecimal number nn; for example, x0A is the same as n 9 uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, u0009 is the same as t 10 cX The control character ^X; for example, cJ is equivalent to the newline character n Meta-characters A meta-character is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for a large sum of money using the ”d” meta-character: /([d]+)000/. Here, d will search for any string of the numerical character. The following table lists a set of meta-characters which can be used in PERL Style Regular Expressions. Sr.No Character & Description 1 . A single character
ES6 – Strings
ES6 – Strings ”; Previous Next The String object lets you work with a series of characters; it wraps JavaScript’s string primitive data type with a number of helper methods. As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive. Use the following syntax to create a String object. var val = new String(string); The string parameter is a series of characters that has been properly encoded. String. String Properties Following is a list of the properties of String object and its description. Sr.No Property & Description 1 constructor Returns a reference to the String function that created the object . 2 length Returns the length of the string. 3 Prototype The prototype property allows you to add properties and methods to an object . String Methods Here is a list of the methods available in String object along with their description. Sr.No Method & Description 1 charAt() Returns the character at the specified index. 2 charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 3 concat() Combines the text of two strings and returns a new string. 4 indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 5 lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 6 localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in a sorted order. 7 match() Used to match a regular expression against a string. 8 replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. 9 search() Executes the search for a match between a regular expression and a specified string. 10 slice() Extracts a section of a string and returns a new string. 11 split() Splits a String object into an array of strings by separating the string into substrings. 12 substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 13 substring() Returns the characters in a string between two indexes into the string. 14 toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale. 15 toLocaleupperCase() The characters within a string are converted to uppercase while respecting the current locale. 16 toLowerCase() Returns the calling string value converted to lowercase. 17 toString() Returns a string representing the specified object. 18 toUpperCase() Returns the calling string value converted to uppercase. 19 valueOf() Returns the primitive value of the specified object. Print Page Previous Next Advertisements ”;
ES6 – Boolean
ES6 – Boolean ”; Previous Next The Boolean object represents two values, either “true” or “false”. If the value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (“”), the object has an initial value of false. Use the following syntax to create a boolean object. var val = new Boolean(value); Boolean Properties Following is a list of the properties of Boolean object. Sr.No Property & Description 1 constructor Returns a reference to the Boolean function that created the object. 2 prototype The prototype property allows you to add properties and methods to an object. Boolean Methods Following is a list of the methods of Boolean object and their description. Sr.No Method & Description 1 toSource() Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object. 2 toString() Returns a string of either “true” or “false” depending upon the value of the object. 3 valueOf() Returns the primitive value of the Boolean object. In the following sections, we will take a look at a few examples to demonstrate the usage of the Boolean methods. Print Page Previous Next Advertisements ”;
ES6 – Maps And Sets
ES6 – Maps and Sets ”; Previous Next ES6 introduces two new data structures − maps and sets. Let us learn about them in detail. Maps A map is an ordered collection of key-value pairs. Maps are similar to objects. However, there are some differences between maps and objects. These are listed below − Sr.No Object Map 1 Keys cannot be Object type Keys can be any type 2 Keys are not ordered Keys are ordered 3 not iterable iterable Syntax The syntax for Map is given below − let map = new Map([iterable]) let map = new Map() Example The following example creates a map using an iterable constructor − <script> let andy = {ename:”Andrel”}, varun = {ename:”Varun”}, prijin = {ename:”Prijin”} let empJobs = new Map([ [andy,”Software Architect”], [varun,”Developer”]] ); console.log(empJobs) </script> The output of the above code is as shown below − {{…} => “Software Architect”, {…} => “Developer”} Checking size of the map The size property can be used to determine the number of values stored in the map. Syntax The syntax for checking the size of the map is given below − map_name.size Example <script> let daysMap = new Map(); daysMap.set(”1”, ”Monday”); daysMap.set(”2”, ”Tuesday”); daysMap.set(”3”, ”Wednesday”); console.log(daysMap.size); </script> The output of the above code is as shown below − 3 Following are some common methods that can be used to manipulate maps − Sr.No Object & Map 1 set(key,value) Adds key and value to map 2 get(key) Returns value if key is matched 3 has(key) Returns true if an element with the specified key exists; else returns false 4 keys() Returns an iterator that contains the keys for each element in the map object 5 values() Returns an iterator that contains the values for each element in the map object 6 entries() Returns an iterator that contains the key-value pairs for each element in the Map 7 delete(key) Removes the specified element from a Map object WeakMap WeakMap is a small subset of map. Keys are weakly referenced, so it can be non-primitive only. If there are no reference to the object keys, it will be subject to garbage collection. not iterable every key is object type The WeakMap will allow garbage collection if the key has no reference. Syntax The syntax for WeakMap is stated below − new WeakMap([iterable]) Example 1 <script> let emp = new WeakMap(); emp.set(10,”Sachin”);// TypeError as keys should be object </script> Example 2 <script> let empMap = new WeakMap(); // emp.set(10,”Sachin”);// Error as keys should be object let e1= {ename:”Kiran”}, e2 = {ename:”Kannan”}, e3 = {ename:”Mohtashim”} empMap.set(e1,1001); empMap.set(e2,1002); empMap.set(e3,1003); console.log(empMap) console.log(empMap.get(e2)) console.log(empMap.has(e2)) empMap.delete(e1) console.log(empMap) </script> The output of the above code is as mentioned below − {{…} => 1002, {…} => 1003, {…} => 1001} 1002 true {{…} => 1002, {…} => 1003} Set A set is an unordered collection of unique values. This data structure can contain values of primitive and object types. Syntax The syntax for Set is given below − new Set([iterable]) new Set() Example <script> let names = new Set([”A”,”B”,”C”,”D”]); console.log(names) </script> The output of the above code is as given below − {“A”, “B”, “C”, “D”} Checking the size of a set The size property of the Set object can be used to query the number of elements in the Set. Syntax The syntax for checking the size of a set is mentioned below − set.size Example <script> let names = new Set([”A”,”B”,”C”,”D”]); console.log(names.size) </script> The output of the above code is as given below − 4 Iterating a Set We can use the forEach and for..of loops to iterate through a Set. This is shown in the example below − Example <script> let names= new Set([”A”,”B”,”C”,”D”]); //iterate using forEach console.log(”forEach”) names.forEach(n=>console.log(n)) console.log(”for of..”) //iterate using for..of for(let n of names){ console.log(n) } </script> The output of the above code is as mentioned below − forEach A B C D for of.. A B C D The following methods can be used to manipulate a set − Sr.No Object & Map 1 add(element) Adds an element to the Set 2 has(element) Returns true if element found; else returns false 3 delete(element) Delete specific element from the Set 4 clear() Clears all elements from the Set WeakSet A Weakset holds objects weakly, that means object stored in a WeakSet are subject to garbage collection, if they are not referenced. WeakSets are not iterable and do not have the get method. <script> let e1 = {ename:”A”} let e2 ={ename:”B”} let e3 ={ename:”C”} let emps = new WeakSet(); emps.add(e1); emps.add(e2) .add(e3); console.log(emps) console.log(emps.has(e1)) emps.delete(e1); console.log(emps) </script> The output of the above code will be as mentioned below − WeakSet {{…}, {…}, {…}} true WeakSet {{…}, {…}} Print Page Previous Next
ES6 – Iterator
ES6 – Iterator ”; Previous Next Introduction to Iterator Iterator is an object which allows us to access a collection of objects one at a time. The following built-in types are by default iterable − String Array Map Set An object is considered iterable, if the object implements a function whose key is [Symbol.iterator] and returns an iterator. A for…of loop can be used to iterate a collection. Example The following example declares an array, marks, and iterates through it by using a for..of loop. <script> let marks = [10,20,30] //check iterable using for..of for(let m of marks){ console.log(m); } </script> The output of the above code will be as given below − 10 20 30 Example The following example declares an array, marks and retrieves an iterator object. The [Symbol.iterator]() can be used to retrieve an iterator object. The next() method of the iterator returns an object with ”value” and ”done” properties . ”done” is Boolean and returns true after reading all items in the collection. <script> let marks = [10,20,30] let iter = marks[Symbol.iterator](); console.log(iter.next()) console.log(iter.next()) console.log(iter.next()) console.log(iter.next()) </script> The output of the above code will be as shown below − {value: 10, done: false} {value: 20, done: false} {value: 30, done: false} {value: undefined, done: true} Custom Iterable Certain types in JavaScript are iterable (E.g. Array, Map etc.) while others are not (E.g. Class). JavaScript types which are not iterable by default can be iterated by using the iterable protocol. The following example defines a class named CustomerList which stores multiple customer objects as an array. Each customer object has firstName and lastName properties. To make this class iterable, the class must implement [Symbol.iterator]() function. This function returns an iterator object. The iterator object has a function next which returns an object {value:”customer”,done:true/false}. <script> //user defined iterable class CustomerList { constructor(customers){ //adding customer objects to an array this.customers = [].concat(customers) } //implement iterator function [Symbol.iterator](){ let count=0; let customers = this.customers return { next:function(){ //retrieving a customer object from the array let customerVal = customers[count]; count+=1; if(count<=customers.length){ return { value:customerVal, done:false } } //return true if all customer objects are iterated return {done:true} } } } } //create customer objects let c1={ firstName:”Sachin”, lastName:”Tendulkar” } let c2={ firstName:”Rahul”, lastName:”Dravid” } //define a customer array and initialize it let customers=[c1,c2] //pass customers to the class” constructor let customersObj = new CustomerList(customers); //iterating using for..of for(let c of customersObj){ console.log(c) } //iterating using the next() method let iter = customersObj[Symbol.iterator](); console.log(iter.next()) console.log(iter.next()) console.log(iter.next()) </script> The output of the above code will be as follows − {firstName: “Sachin”, lastName: “Tendulkar”} {firstName: “Rahul”, lastName: “Dravid”} { done: false value: { firstName: “Sachin”, lastName: “Tendulkar” } } { done: false value: { firstName: “Rahul”, lastName: “Dravid” } } {done: true} Generator Prior to ES6, functions in JavaScript followed a run-to completion model. ES6 introduces functions known as Generator which can stop midway and then continue from where it stopped. A generator prefixes the function name with an asterisk * character and contains one or more yield statements. The yield keyword returns an iterator object. Syntax function * generator_name() { yield value1 … yield valueN } Example The example defines a generator function getMarks with three yield statements. Unlike normal functions, the generator function getMarks(),when invoked, doesn’t execute the function but returns an iterator object that helps you to execute code inside the generator function. On the first call to markIter.next() operations in the beginning would run and the yield statement pauses the execution of the generator. Subsequent calls to the markIter.next() will resume the generator function until the next yield expression. <script> //define generator function function * getMarks(){ console.log(“Step 1”) yield 10 console.log(“Step 2”) yield 20 console.log(“Step 3”) yield 30 console.log(“End of function”) } //return an iterator object let markIter = getMarks() //invoke statements until first yield console.log(markIter.next()) //resume execution after the last yield until second yield expression console.log(markIter.next()) //resume execution after last yield until third yield expression console.log(markIter.next()) console.log(markIter.next()) // iteration is completed;no value is returned </script> The output of the above code will be as mentioned below − Step 1 {value: 10, done: false} Step 2 {value: 20, done: false} Step 3 {value: 30, done: false} End of function {value: undefined, done: true} Example The following example creates an infinite sequence of even numbers through * evenNumberGenerator generator function. We can iterate through all even numbers by using next() or using for of loop as shown below <script> function * evenNumberGenerator(){ let num = 0; while(true){ num+=2 yield num } } // display first two elements let iter = evenNumberGenerator(); console.log(iter.next()) console.log(iter.next()) //using for of to iterate till 12 for(let n of evenNumberGenerator()){ if(n==12)break; console.log(n); } </script> The output of the above code will be as follows − {value: 2, done: false} {value: 4, done: false} 2 4 6 8 10 Print Page Previous Next Advertisements ”;
ES6 – HTML DOM
ES6 – HTML DOM ”; Previous Next Every web page resides inside a browser window, which can be considered as an object. A document object represents the HTML document that is displayed in that window. The document object has various properties that refer to other objects which allow access to and modification of the document content. The way a document content is accessed and modified is called the Document Object Model, or DOM. The objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a web document. Following is a simple hierarchy of a few important objects − There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify the document content. The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images. The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers. The IE4 DOM − This document object model was introduced in Version 4 of Microsoft”s Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features. The Legacy DOM This is the model which was introduced in the early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of the documents, such as forms, form elements, and images. This model provides several read-only properties, such as title, URL, and lastModified provide information about the document as a whole. Apart from that, there are various methods provided by this model which can be used to set and get the document property values. Document Properties in Legacy DOM Following is a list of the document properties which can be accessed using Legacy DOM. Sr.No Property & Description 1 alinkColor Deprecated − A string that specifies the color of activated links. Example : document.alinkColor 2 anchors[ ] An array of anchor objects, one for each anchor that appears in the document. Example : document.anchors[0], document.anchors[1] and so on 3 applets[ ] An array of applet objects, one for each applet that appears in the document. Example : document.applets[0], document.applets[1] and so on 4 bgColor Deprecated − A string that specifies the background color of the document. Example : document.bgColor 5 Cookie A string valued property with special behavior that allows the cookies associated with this document to be queried and set. Example : document.cookie 6 Domain A string that specifies the Internet domain the document is from. Used for security purposes. Example : document.domain 7 embeds[ ] An array of objects that represent data embedded in the document with the <embed> tag. A synonym for plugins []. Some plugins and ActiveX controls can be controlled with JavaScript code. Example : document.embeds[0], document.embeds[1] and so on 8 fgColor A string that specifies the default text color for the document. Example : document.fgColor 9 forms[ ] An array of form objects, one for each HTML form that appears in the document. Example : document.forms[0], document.forms[1] and so on 10 images[ ] An array of form objects, one for each HTML form that appears in the document with the HTML <img> tag. Example : document.forms[0], document.forms[1] and so on 11 lastModified A read-only string that specifies the date of the most recent change to the document. Example : document.lastModified 12 linkColor Deprecated − A string that specifies the color of unvisited links. Example : document.linkColor 13 links[ ] It is a document link array. Example : document.links[0], document.links[1] and so on 14 Location The URL of the document. Deprecated in favor of the URL property. Example : document.location 15 plugins[ ] A synonym for the embeds[ ] Example : document.plugins[0], document.plugins[1] and so on 16 Referrer A read-only string that contains the URL of the document, if any, from which the current document was linked. Example : document.referrer 17 Title The text contents of the <title> tag. Example : document.title 18 URL A read-only string that specifies the URL of the document. Example : document.URL 19 vlinkColor Deprecated − A string that specifies the color of the visited links. Example : document.vlinkColor Document Methods in Legacy DOM Following is a list of methods supported by Legacy DOM. Sr.No Property & Description 1 clear( ) Deprecated − Erases the contents of the document and returns nothing. Example : document.clear( ) 2 close( ) Closes a document stream opened with the open( ) method and returns nothing.
ES6 – Animation
ES6 – Animation ”; Previous Next You can use JavaScript to create a complex animation having, but not limited to, the following elements − Fireworks Fade effect Roll-in or Roll-out Page-in or Page-out Object movements In this chapter, we will see how to use JavaScript to create an animation. JavaScript can be used to move a number of DOM elements (<img />, <div>, or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function. JavaScript provides the following functions to be frequently used in animation programs. setTimeout(function, duration) − This function calls the function after duration milliseconds from now. setInterval(function, duration) − This function calls the function after every duration milliseconds. clearTimeout(setTimeout_variable) − This function clears any timer set by the setTimeout() function. JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set the top and the left attribute of an object to position it anywhere on the screen. Following is the syntax for the same. // Set distance from left edge of the screen. object.style.left = distance in pixels or points; or // Set distance from top edge of the screen. object.style.top = distance in pixels or points; Manual Animation So let”s implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods. We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj. We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes. We are calling initialization function at the time of window load. We are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side. Example Try the following example <html> <head> <title>JavaScript Animation</title> <script type = “text/javascript”> <!– var imgObj = null; function init(){ imgObj = document.getElementById(”myImage”); imgObj.style.position = ”relative”; imgObj.style.left = ”0px”; } function moveRight(){ imgObj.style.left = parseInt( imgObj.style.left) + 10 + ”px”; } window.onload = init; // –> </script> </head> <body> <form> <img id = “myImage” src = “/images/html.gif” /> <p>Click button below to move the image to right</p> <input type = “button” value = “Click Me” onclick = “moveRight();” /> </form> </body> </html> Automated Animation In the above example, we saw how an image moves to the right with every click. We can automate this process by using the JavaScript function setTimeout() as follows. Here we have added more methods. So, let”s see what is new here. The moveRight() function is calling setTimeout() function to set the position of imgObj. We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position. Example Try the following example code. <html> <head> <title>JavaScript Animation</title> <script type = “text/javascript”> <!– var imgObj = null; var animate ; function init(){ imgObj = document.getElementById(”myImage”); imgObj.style.position = ”relative”; imgObj.style.left = ”0px”; } function moveRight(){ imgObj.style.left = parseInt(imgObj.style.left) + 10 + ”px”; animate = setTimeout(moveRight,20); // call moveRight in 20msec } function stop() { clearTimeout(animate); imgObj.style.left = ”0px”; } window.onload = init; // –> </script> </head> <body> <form> <img id = “myImage” src = “/images/html.gif” /> <p>Click the buttons below to handle animation</p> <input type=”button” value=”Start” onclick = “moveRight();” /> <input type = “button” value=”Stop” onclick = “stop();” /> </form> </body> </html> Rollover with a Mouse Event Here is a simple example showing the image rollover with a mouse event. Let”s see what we are using in the following example − At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed. The Image() constructor creates and preloads a new image object called image1. The src property is assigned the name of the external image file called /images/html.gif. Similarly, we have created image2 object and assigned /images/http.gif in this object. The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image. The onMouseOver event handler is triggered when the user”s mouse moves onto the link, and the onMouseOut event handler is triggered when the user”s mouse moves away from the link (image). When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed. When the mouse is moved away from the link, the initial image html.gif will reappear on the screen. <html> <head> <title>Rollover with a Mouse Events</title> <script type = “text/javascript”> <!– if(document.images) { var image1 = new Image(); // Preload an image image1.src = “/images/html.gif”; var image2 = new Image(); // Preload second image image2.src = “/images/http.gif”; } // –> </script> </head> <body> <p>Move your mouse over the image to see the result</p> <a href = “#” onMouseOver = “document.myImage.src = image2.src;” onMouseOut = “document.myImage.src = image1.src;”> <img name = “myImage” src = “/images/html.gif”
ES6 – Date
ES6 – Date ”; Previous Next The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date () as shown in the following syntax. Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755. You can use any of the following syntax to create a Date object using Date () constructor. new Date( ) new Date(milliseconds) new Date(datestring) new Date(year,month,date[,hour,minute,second,millisecond ]) Note − Parameters in the brackets are always optional. Date Properties Here is a list of the properties of the Date object along with their description. Sr.No Property & Description 1 constructor Specifies the function that creates an object”s prototype 2 prototype The prototype property allows you to add properties and methods to an object Date Methods Following is a list of different date methods along with the description. Sr.No Method & Description 1 Date() Returns today”s date and time 2 getDate() Returns the day of the month for the specified date according to the local time 3 getDay() Returns the day of the week for the specified date according to the local time 4 getFullYear() Returns the year of the specified date according to the local time 5 getHours() Returns the hour in the specified date according to the local time 6 getMilliseconds() Returns the milliseconds in the specified date according to the local time 7 getMinutes() Returns the minutes in the specified date according to the local time 8 getMonth() Returns the month in the specified date according to the local time 9 getSeconds() Returns the seconds in the specified date according to the local time 10 getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC 11 getTimezoneOffset() Returns the time-zone offset in minutes for the current locale 12 getUTCDate() Returns the day (date) of the month in the specified date according to the universal time 13 getUTCDay() Returns the day of the week in the specified date according to the universal time 14 getUTCFullYear() Returns the year in the specified date according to the universal time 15 getutcHours() Returns the hours in the specified date according to the universal time 16 getUTCMilliseconds() Returns the milliseconds in the specified date according to the universal time 17 getUTCMinutes() Returns the minutes in the specified date according to the universal time 18 getUTCMonth() Returns the month in the specified date according to the universal time 19 getUTCSeconds() Returns the seconds in the specified date according to the universal time 20 setDate() Sets the day of the month for a specified date according to the local time 21 setFullYear() Sets the full year for a specified date according to the local time 22 setHours() Sets the hours for a specified date according to the local time 23 setMilliseconds() Sets the milliseconds for a specified date according to the local time 24 setMinutes() Sets the minutes for a specified date according to the local time 25 setMonth() Sets the month for a specified date according to the local time 26 setSeconds() Sets the seconds for a specified date according to the local time 27 setTime() Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC 28 setUTCDate() Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC 29 setUTCFullYear() Sets the full year for a specified date according to the universal time 30 setUTCHours() Sets the hour for a specified date according to the universal time 31 setUTCMilliseconds() Sets the milliseconds for a specified date according to the universal time 32 setUTCMinutes() Sets the minutes for a specified date according to the universal time 33 setUTCMonth() Sets the month for a specified date according to the universal time 34 setUTCSeconds() Sets the seconds for a specified date according to the universal time 35 todatestring() Returns the “date” portion of the Date as a human-readable string