ES6 – Page Printing

ES6 – Page Printing ”; Previous Next Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you implement this functionality using the print function of the window object. The JavaScript print function window.print() prints the current webpage when executed. You can call this function directly using the onclick event as shown in the following example. Example <html> <body> <form> <input type = “button” value = “Print” onclick = “window.print()”/> </form> </body> </html> The following output is displayed on successful execution of the above code. Print Page Previous Next Advertisements ”;

ES6 – Void Keyword

ES6 – void Keyword ”; Previous Next void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value. The operator evaluates a given expression and then returns undefined. Following is the syntax for the same. void expression Void and Immediately Invoked Function Expressions When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. Consider the following example − void function iife_void() { var msg = function () {console.log(“hello world”)}; msg(); }(); The following output is displayed on successful execution of the above code. hello world Void and JavaScript URIs The JavaScript: URI is a commonly encountered syntax in a HTML page. The browser evaluates the URI and replaces the content of the page with the value returned. This is true unless the value returned is undefined. The most common use of this operator is in a client-side JavaScript: URL, where it allows you to evaluate an expression for its side effects without the browser displaying the value of the evaluated expression. Consider the following code snippet − <a href = “javascript:void(javascript:alert(”hello world!!”))”> Click here to do nothing </a> <br/><br/><br/> <a href = “javascript:alert(”hello”);”>Click here for an alert</a> Save the above file as an HTML document and open it in the browser. The first hyperlink, when clicked evaluates the javascript :alert(“hello”) and is passed to the void() operator. However, since the void operator returns undefined, no result is displayed on the page. On the other hand, the second hyperlink when clicked displays an alert dialog. Print Page Previous Next Advertisements ”;

ES6 – Events

ES6 – Events ”; Previous Next JavaScript is meant to add interactivity to your pages. JavaScript does this using a mechanism using events. Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events that can trigger JavaScript Code. An event is an action or occurrence recognized by the software. It can be triggered by a user or the system. Some common examples of events include a user clicking on a button, loading the web page, clicking on a hyperlink and so on. Following are some of the common HTML events. Event Handlers On the occurrence of an event, the application executes a set of related tasks. The block of code that achieves this purpose is called the eventhandler. Every HTML element has a set of events associated with it. We can define how the events will be processed in JavaScript by using event handlers. onclick Event Type This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning, etc. against this event type. Example <html> <head> <script type = “text/javascript”> function sayHello() { document.write (“Hello World”) } </script> </head> <body> <p> Click the following button and see result</p> <input type = “button” onclick = “sayHello()” value = “Say Hello” /> </body> </html> The following output is displayed on successful execution of the above code. onsubmitEvent Type onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data. Example <html> <head> <script type = “text/javascript”> function validation() { all validation goes here ……… return either true or false } </script> </head> <body> <form method = “POST” action = “t.cgi” onsubmit = “return validate()”> ……. <input type = “submit” value = “Submit” /> </form> </body> </html> onmouseover and onmouseout These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Example <html> <head> <script type = “text/javascript”> function over() { document.write (“Mouse Over”); } function out() { document.write (“Mouse Out”); } </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover = “over()” onmouseout = “out()”> <h2> This is inside the division </h2> </div> </body> </html> The following output is displayed on successful execution of the above code. HTML 5 Standard Events The standard HTML 5 events are listed in the following table for your reference. The script indicates a JavaScript function to be executed against that event. Attribute Value Description offline script Triggers when the document goes offline onabort script Triggers on an abort event onafterprint script Triggers after the document is printed onbeforeonload script Triggers before the document load onbeforeprint script Triggers before the document is printed onblur script Triggers when the window loses focus oncanplay script Triggers when the media can start play, but might have to stop for buffering oncanplaythrough script Triggers when the media can be played to the end, without stopping for buffering onchange script Triggers when an element changes onclick script Triggers on a mouse click oncontextmenu script Triggers when a context menu is triggered ondblclick script Triggers on a mouse double-click ondrag script Triggers when an element is dragged ondragend script Triggers at the end of a drag operation ondragenter script Triggers when an element has been dragged to a valid drop target ondragleave script Triggers when an element leaves a valid drop target ondragover script Triggers when an element is being dragged over a valid drop target ondragstart script Triggers at the start of a drag operation ondrop script Triggers when the dragged element is being dropped ondurationchange script Triggers when the length of the media is changed onemptied script Triggers when a media resource element suddenly becomes empty onended script Triggers when the media has reached the end onerror script Triggers when an error occurs onfocus script Triggers when the window gets focus onformchange script Triggers when a form changes onforminput script Triggers when a form gets user input onhaschange script Triggers when the document has changed oninput script Triggers when an element gets user input oninvalid script Triggers when an element is invalid

ES6 – New String Methods

ES6 – New String Methods ”; Previous Next Following is a list of methods with their description. Sr.No Method & Description 1 String.prototype.startsWith(searchString, position = 0) Returns true if the receiver starts with searchString; the position lets you specify where the string to be checked starts. 2 String.prototype.endsWith(searchString, endPosition = searchString.length) Returns true if the receiver starts with searchString; the position lets you specify where the string to be checked starts. 3 String.prototype.includes(searchString, position = 0) Returns true if the receiver contains searchString; position lets you specify where the string to be searched starts. 4 String.prototype.repeat(count) Returns the receiver, concatenated count times. Template Literals Template literals are string literals that allow embedded expressions. Templatestrings use back-ticks (“) rather than the single or double quotes. A template string could thus be written as − var greeting = `Hello World!`; String Interpolation and Template literals Template strings can use placeholders for string substitution using the ${ } syntax, as demonstrated. Example 1 var name = “Brendan”; console.log(”Hello, ${name}!”); The following output is displayed on successful execution of the above code. Hello, Brendan! Example 2: Template literals and expressions var a = 10; var b = 10; console.log(`The sum of ${a} and ${b} is ${a+b} `); The following output is displayed on successful execution of the above code. The sum of 10 and 10 is 20 Example 3: Template literals and function expression function fn() { return “Hello World”; } console.log(`Message: ${fn()} !!`); The following output is displayed on successful execution of the above code. Message: Hello World !! Multiline Strings and Template Literals Template strings can contain multiple lines. Example var multiLine = ` This is a string with multiple lines`; console.log(multiLine) The following output is displayed on successful execution of the above code. This is a string with multiple line String.raw() ES6 includes the tag function String.raw for raw strings, where backslashes have no special meaning. String.raw enables us to write the backslash as we would in a regular expression literal. Consider the following example. var text =`Hello n World` console.log(text) var raw_text = String.raw`Hello n World ` console.log(raw_text) The following output is displayed on successful execution of the above code. Hello World Hello n World Tagged Templates A tag is a function which can interpret and process a template literal. A tag appears in front of the template literal. Syntax is shown below. Syntax let output_fromTag = tagFunction `Template literal with ${variable1} , ${variable2}` The tag function implementation syntax is as given below − function tagFunction(literals,…variable_values){ //process return “some result” } Example Following Example defines a tag function myTagFn(). It displays the parameters passed to it. After displaying it returns Done to the caller. <script> function myTagFn(literals,…values){ console.log(“literal values are”); for(let c of literals){ console.log(c) } console.log(“variable values are “); for(let c of values){ console.log(c) } return “Done” } let company = `TutorialsPoint` let company_location = `Mumbai` let result = myTagFn `Hello this is ${company} from ${company_location}` console.log(result) </script> The output of the above code will be as stated below − //literal literal values are Hello this is from //values variable values are TutorialsPoint Mumbai Done Example The below tag function takes a template literal and converts it to upper case as shown below − <script> function convertToUpperTagFn(literals, …values) { let result = “”; for (let i = 0; i < literals.length; i++) { result += literals[i]; if (i < values.length) { result += values[i]; } } return result.toUpperCase(); } let company = `TutorialsPoint` let company_location = `Mumbai` let result = convertToUpperTagFn `Hello this is ${company} from ${company_location}` console.log(result) </script> The output of the above code will be as mentioned below − HELLO THIS IS TUTORIALSPOINT FROM MUMBAI String.fromCodePoint() The static String.fromCodePoint() method returns a string created by using the specified sequence of unicode code points. The function throws a RangeError if an invalid code point is passed. console.log(String.fromCodePoint(42)) console.log(String.fromCodePoint(65, 90)) The following output is displayed on successful execution of the above code. * AZ Print Page Previous Next Advertisements ”;

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

ES6 – Dialog Boxes

ES6 – Dialog Boxes ”; Previous Next JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one. Alert Dialog Box An alert dialog box is mostly used to send a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to send a warning message. Nonetheless, an alert box can still be used for friendlier messages. Alert box provides only one button “OK” to select and proceed. Example <html> <head> <script type = “text/javascript”> function Warn() { alert (“This is a warning message!”); document.write (“This is a warning message!”); } </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = “button” value = “Click Me” onclick = “Warn();” /> </form> </body> </html> The following output is displayed on successful execution of the above code. Confirmation Dialog Box A confirmation dialog box is mostly used to take the user”s consent on any option. It displays a dialog box with two buttons: OK and Cancel. If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows. Example <html> <head> <script type = “text/javascript”> function getConfirmation(){ var retVal = confirm(“Do you want to continue ?”); if( retVal == true ){ document.write (“User wants to continue!”); return true; } else { Document.write (“User does not want to continue!”); return false; } } </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = “button” value = “Click Me” onclick = “getConfirmation();” /> </form> </body> </html> The following output is displayed on successful execution of the above code. Prompt Dialog Box The prompt dialog box is very useful when you want to pop-up a text box to get a user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box. This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null. Example <html> <head> <script type = “text/javascript”> function getValue(){ var retVal = prompt(“Enter your name : “, “your name here”); document.write(“You have entered : ” + retVal); } </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = “button” value = “Click Me” onclick = “getValue();” /> </form> </body> </html> The following output is displayed on successful execution of the above code. Print Page Previous Next Advertisements ”;

ES6 – Operators

ES6 – Operators ”; Previous Next An expression is a special kind of statement that evaluates to a value. Every expression is composed of − Operands − Represents the data. Operator − Defines how the operands will be processed to produce a value. Consider the following expression- 2 + 3. Here in the expression, 2 and 3 are operands and the symbol + (plus) is the operator. JavaScript supports the following types of operators − Arithmetic operators Logical operators Relational operators Bitwise operators Assignment operators Ternary/conditional operators String operators Type operators The void operator Arithmetic Operators Assume the values in variables a and b are 10 and 5 respectively. Show Examples Operator Function Example + Addition Returns the sum of the operands. a + b is 15 – Subtraction Returns the difference of the values. a-b is 5 * Multiplication Returns the product of the values. a*b is 50 / Division Performs a division operation and returns the quotient. a/b is 2 % Modulus Performs a division and returns the remainder. a%b is 0 ++ Increment Increments the value of the variable by one. a++ is 11 — Decrement Decrements the value of the variable by one. a– is 9 Relational Operators Relational operators test or define the kind of relationship between two entities. Relational operators return a boolean value, i.e. true/false. Assume the value of A is 10 and B is 20. Show Examples Operators Description Example > Greater than (A > B) is False < Lesser than (A < B) is True >= Greater than or equal to (A >= B) is False <= Lesser than or equal to (A <= B) is True == Equality (A == B) is False != Not Equal (A!= B) is True Logical Operators Logical operators are used to combine two or more conditions. Logical operators, too, return a Boolean value. Assume the value of variable A is 10 and B is 20. Show Examples. Operators Description Example && And The operator returns true only if all the expressions specified return true. (A > 10 && B > 10) is False || Or The operator returns true if at least one of the expressions specified return true. (A > 10 || B > 10) is True ! Not The operator returns the inverse of the expression’s result. For E.g.: !(7>5) returns false. !(A > 10) is True Bitwise Operators JavaScript supports the following bitwise operators. The following table summarizes JavaScript”s bitwise operators. Show Examples. Operators Usage Description Bitwise AND a & b Returns a one in each bit position for which the corresponding bits of both operands are ones Bitwise OR a | b Returns a one in each bit position for which the corresponding bits of either or both operands are ones Bitwise XOR a^b Returns a one in each bit position for which the corresponding bits of either but not both operands are ones Bitwise NOT ~ a Inverts the bits of its operand Left shift a << b Shifts a in binary representation b (< 32) bits to the left, shifting in zeroes from the right Sign-propagating right shift a >> b Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off Zero-fill right shift a >>> b Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeroes from the left Assignment Operators The following table summarizes Assignment operators. Show Examples. Sr.No Operator & Description 1 = (Simple Assignment) Assigns values from the right side operand to the left side operand. Example − C = A + B will assign the value of A + B into C 2 += (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. Example − C += A is equivalent to C = C + A 3 -= (Subtract and Assignment) It subtracts the right operand from the left operand and assigns the result to the left operand. Example C -= A is equivalent to C = C – A 4 *= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the left operand. Example C *= A is equivalent to C = C * A 5 /= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left operand. Note − The same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |= and ^=. Miscellaneous Operators Following are some of the

ES6 – Objects

ES6 – Objects ”; Previous Next JavaScript supports extending data types. JavaScript objects are a great way to define custom data types. An object is an instance which contains a set of key value pairs. Unlike primitive data types, objects can represent multiple or complex values and can change over their life time. The values can be scalar values or functions or even array of other objects. The syntactic variations for defining an object is discussed further. Object Initializers Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object. var identifier = { Key1:value, Key2: function () { //functions }, Key3: [“content1”,” content2”] } The contents of an object are called properties (or members), and properties consist of a name (or key) and value. Property names must be strings or symbols, and values can be any type (including other objects). Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation. Following is the syntax for accessing Object Properties. objectName.propertyName Example: Object Initializers var person = { firstname:”Tom”, lastname:”Hanks”, func:function(){return “Hello!!”}, }; //access the object values console.log(person.firstname) console.log(person.lastname) console.log(person.func()) The above Example, defines an object person. The object has three properties. The third property refers to a function. The following output is displayed on successful execution of the above code. Tom Hanks Hello!! In ES6, assigning a property value that matches a property name, you can omit the property value. Example var foo = ”bar” var baz = { foo } console.log(baz.foo) The above code snippet defines an object baz. The object has a property foo. The property value is omitted here as ES6 implicitly assigns the value of the variable foo to the object’s key foo. Following is the ES5 equivalent of the above code. var foo = ”bar” var baz = { foo:foo } console.log(baz.foo) The following output is displayed on successful execution of the above code. bar With this shorthand syntax, the JS engine looks in the containing scope for a variable with the same name. If it is found, that variable’s value is assigned to the property. If it is not found, a Reference Error is thrown. The Object() Constructor JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. Following is the syntax for defining an object. var obj_name = new Object(); obj_name.property = value; OR obj_name[“key”] = value Following is the syntax for accessing a property. Object_name.property_key OR Object_name[“property_key”] Example var myCar = new Object(); myCar.make = “Ford”; //define an object myCar.model = “Mustang”; myCar.year = 1987; console.log(myCar[“make”]) //access the object property console.log(myCar[“model”]) console.log(myCar[“year”]) The following output is displayed on successful execution of the above code. Ford Mustang 1987 Unassigned properties of an object are undefined. Example var myCar = new Object(); myCar.make = “Ford”; console.log(myCar[“model”]) The following output is displayed on successful execution of the above code. undefined Note − An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. Properties can also be accessed by using a string value that is stored in a variable. In other words, the object’s property key can be a dynamic value. For example: a variable. The said concept is illustrated in the following example. Example var myCar = new Object() var propertyName = “make”; myCar[propertyName] = “Ford”; console.log(myCar.make) The following output is displayed on successful execution of the above code. Ford Constructor Function An object can be created using the following two steps − Step 1 − Define the object type by writing a constructor function. Following is the syntax for the same. function function_name() { this.property_name = value } The ‘this’ keyword refers to the current object in use and defines the object’s property. Step 2 − Create an instance of the object with the new syntax. var Object_name= new function_name() //Access the property value Object_name.property_name The new keyword invokes the function constructor and initializes the function’s property keys. Example − Using a Function Constructor function Car() { this.make = “Ford” this.model = “F123” } var obj = new Car() console.log(obj.make) console.log(obj.model) The above example uses a function constructor to define an object. The following output is displayed on successful execution of the above code. Ford F123 A new property can always be added to a previously defined object. For example, consider the following code snippet − function Car() { this.make = “Ford” } var obj = new Car() obj.model = “F123” console.log(obj.make) console.log(obj.model) The following output is displayed on successful execution of the above code. Ford F123 The Object.create Method Objects can also

ES6 – Overview

ES6 – Overview ”; Previous Next ECMAScript (ES) is a scripting language specification standardized by ECMAScript International. It is used by applications to enable client-side scripting. The specification is influenced by programming languages like Self, Perl, Python, Java etc. Languages like JavaScript, Jscript and ActionScript are governed by this specification. This tutorial introduces you to ES6 implementation in JavaScript. JavaScript JavaScript was developed by Brendan Eich, a developer at Netscape Communications Corporation, in 1995.JavaScript started life with the name Mocha, and was briefly named LiveScript before being officially renamed to JavaScript. It is a scripting language that is executed by the browser, i.e. on the client’s end. It is used in conjunction with HTML to develop responsive webpages. ECMA Script6’s implementation discussed here covers the following new features − Support for constants Block Scope Arrow Functions Extended Parameter Handling Template Literals Extended Literals Enhanced Object Properties De-structuring Assignment Modules Classes Iterators Generators Collections New built in methods for various classes Promises ECMAScript Versions There are nine editions of ECMA-262 which are as follows − Edition Name Description 1 ECMAScript 1 First Edition released in 1997 2 ECMAScript 2 Second Edition released in 1998, minor changes to meet ISO/IEC 16262 standard 3 ECMAScript 3 Third Edition released in 1999 with language enhancements 4 ECMAScript 4 Fourth Edition release plan was dropped, few features added later in ES6 & other complex features dropped 5 ECMAScript 5 Fifth Edition released in 2009 5.1 ECMAScript 5.1 5.1 Edition released in 2011, minor changes to meet ISO/IEC 16262:2011 standard 6 ECMAScript 2015/ES6 Sixth Edition released in 2015, see ES6 chapters for new features 7 ECMAScript 2016/ES7 Seventh Edition released in 2016, see ES7 chapters for new features 8 ECMAScript 2017/ES8 Eight Edition released in 2017, see ES8 chapters for new features 9 ECMAScript 2018/ES9 Ninth Edition released in 2018, see ES9 chapters for new features Print Page Previous Next Advertisements ”;

ES6 – Syntax

ES6 – Syntax ”; Previous Next Syntax defines the set of rules for writing programs. Every language specification defines its own syntax. A JavaScript program can be composed of − Variables − Represents a named memory block that can store values for the program. Literals − Represents constant/fixed values. Operators − Symbols that define how the operands will be processed. Keywords − Words that have a special meaning in the context of a language. The following table lists some keywords in JavaScript. Some commonly used keywords are listed in the following table. break as any Switch case if throw Else var number string Get module type instanceof Typeof finally for enum Export while void this New null super Catch let static return True False Modules − Represents code blocks that can be reused across different programs/scripts. Comments − Used to improve code readability. These are ignored by the JavaScript engine. Identifiers − These are the names given to elements in a program like variables, functions, etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot be keywords. They must be unique. Identifiers are case sensitive. Identifiers cannot contain spaces. The following table illustrates some valid and invalid identifiers. Examples of valid identifiers Examples of invalid identifiers firstName first_name num1 $result Var# first name first-name 1number Whitespace and Line Breaks ES6 ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. JavaScript is Case-sensitive JavaScript is case-sensitive. This means that JavaScript differentiates between the uppercase and the lowercase characters. Semicolons are Optional Each line of instruction is called a statement. Semicolons are optional in JavaScript. Example console.log(“hello world”) console.log(“We are learning ES6″) A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments in JavaScript Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like the author of the code, hints about a function/construct, etc. Comments are ignored by the compiler. JavaScript supports the following types of comments − Single-line comments (//) − Any text between a // and the end of a line is treated as a comment. Multi-line comments (/* */) − These comments may span multiple lines. Example //this is single line comment /* This is a Multi-line comment */ Your First JavaScript Code Let us start with the traditional “Hello World” example”. var message = “Hello World” console.log(message) The program can be analyzed as − Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program. Line 2 prints the variable’s value to the prompt. Here, the console refers to the terminal window. The function log () is used to display the text on the screen. Executing the Code We shall use Node.js to execute our code. Step 1 − Save the file as Test.js Step 2 − Right-click the Test.js file under the working files option in the project-explorer window of the Visual Studio Code. Step 3 − Select Open in Command Prompt option. Step 4 − Type the following command in Node’s terminal window. node Test.js The following output is displayed on successful execution of the file. Hello World Node.js and JS/ES6 ECMAScript 2015(ES6) features are classified into three groups − For Shipping − These are features that V8 considers stable. Staged Features − These are almost completed features but not considered stable by the V8 team. In Progress − These features should be used only for testing purposes. The first category of features is fully supported and turned on by default by node. Staged features require a runtime – – harmony flag to execute. A list of component specific CLI flags for Node.js can be found here − https://nodejs.org/api/cli.html The Strict Mode The fifth edition of the ECMAScript specification introduced the Strict Mode. The Strict Mode imposes a layer of constraint on JavaScript. It makes several changes to normal JavaScript semantics. The code can be transitioned to work in the Strict Mode by including the following − // Whole-script strict mode syntax “use strict”; v = “Hi! I”m a strict mode script!”; // ERROR: Variable v is not declared In the above snippet, the entire code runs as a constrained variant of JavaScript. JavaScript also allows to restrict, the Strict Mode within a block’s scope as that of a function. This is illustrated as follows − v = 15 function f1() { “use strict”; var v = “Hi! I”m a strict mode script!”; } In, the above snippet, any code outside the function will run in the non-strict mode. All statements within the