What is ES6:

  • ECMAScript, or ES6, was published in June 2015. It was subsequently renamed to ECMAScript 2015.
  • ES6 refers to version 6 of the ECMA Script programming language.
  • It is used by applications to enable client-side scripting. Languages like JavaScript, Jscript and ActionScript are governed by this specification.
  • Web browser support for the full language is not yet complete, though major portions are supported.
  • Major web browsers support some features of ES6. However, it is possible to use software known as a transpiler to convert ES6 code into ES5, which is better supported on most browsers.
  • ECMA Script is the standardized name for JavaScript, and version 6 is the next version after version 5, which was released in 2011.
  • It is a major enhancement to the JavaScript language, and adds many more features intended to make large-scale software development easier.

What’s new in ES6?

ECMA Script6’s implementation has the following new features:

  • Support for constants
  • Block Scope
  • Arrow Functions
  • Default parameters
  • Template literals
  • Rest parameters
  • Spread parameters
  • De-structuring Assignment
  • Modules
  • Classes

Let and Var: [Block Scope]

LET:

  • The let statement declares a block scope local variable, optionally initializing it to a value.
  • let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.
  • This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
  • Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks.
  • In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function.

Syntax:

Example:

VAR:

  • The scope of a variable defined with var is function scope or declared outside any function, global.
  • var declarations, wherever they occur, are processed before any code is executed. This is called hoisting.
  • The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
  • If you re-declare a JavaScript variable, it will not lose its value.
  • Assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed.

Syntax:

Example:

Const:

  • const addresses the common need of developers to associate a mnemonic name with a given value such that the value can’t be changed.
  • Constants defined with const follow the same scope rules as variables.
  • Constants are block-scoped, much like variables defined using the let statement.
  • The value of a constant cannot change through re-assignment, and it can’t be redeclared.
  • This declaration creates a constant whose scope can be either global or local to the block in which it is declared.
  • Global constants do not become properties of the window object, unlike var variables.
  • An initializer for a constant is required; that is, you must specify its value in the same statement in which it’s declared.

Syntax:

Example:

  • In the console you can see the the error as like below,
  • You can check check the answer also, for that go to the sources window and inspect,
  • Having an error while developing is better than having buggy behavior in production, so always prefer the strictness of let and const.

Destructure:

  • ECMAScript 6 (ES2015) destructuring assignment allows you to extract individual items from arrays or objects and place them into variables using a shorthand syntax.
  • It is a convenient way to extract values from data stored in (possibly nested) objects and arrays.
  • Destructuring simply implies breaking down a complex structure into simpler parts.
  • In JavaScript, this complex structure is usually an object or an array.
  • With the destructuring syntax, you can extract smaller fragments from arrays and objects.
  • Destructuring syntax can be used for variable declaration or variable assignment.
  • You can also handle nested structures by using nested destructuring syntax.

Syntax:

Example1:

Example2:

  • You can swap the values by using the commented code also. Instead you can use the destructured code to do the same in a simple way.

Default Parameters:

  • This is the ability to have your functions initialize parameters with default values even if the function call doesn’t include them.
  • Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
  • In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value.
  • In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.

Example:

Rest parameter:

  • In ES5, writing a function with a variable number of parameters required using a special object called arguments.
  • This object is similar to an array, and it contains values corresponding to the arguments passed to a function.
  • The implicit arguments variable could be treated as a local variable in any function.
  • The rest operator is used to pass a variable number of arguments to a function, and it has to be the last one in the arguments list.
  • If the name of the function argument starts with the three dots, the function will get the rest of the arguments in an array.
  • The ES6 rest operator is represented by three dots ().
  • The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Syntax:

Example:

  • In that example, the is a Rest parameter, a syntax allows us to represent an indefinite number of arguments as an array.
  • It is somewhat similar, but it’s not the same as the spread syntax.

Spread parameters:

  • The spread is closely related to rest parameters, because of … (three dots) notation.
  • It allows to split an array to single arguments which are passed to the function as separate arguments.
  • The rest operator can turn a variable number of parameters into an array, the spread operator can do the opposite: turn an array into a list of values or function parameters.
  • Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected, or an object expression to be expanded in places where zero or more key-value pairs are expected.

Syntax:

Example:

Template Literals:

  • Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
  • They were called “template strings” in prior editions of the ES2015 specification.
  • Template literals are enclosed by the back-tick ( ) character instead of double or single quotes.
  • Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
  • The expressions in the placeholders and the text between them get passed to a function. The default function just concatenates the parts into a single string.
  • Template literals are quite simply the easiest way to improve your JavaScript code readability when working with Strings.

Example:

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance.Classes:

  • The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
  • A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.
  • Classes can be included in the code either by declaring them or by using class expressions.

Syntax:


  • The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class.
  • A class definition can include the following :
    • Constructors − Responsible for allocating memory for the objects of the class.
    • Functions − Functions represent actions an object can take. They are also at times referred to as methods.

Example:

Class extends Bankaccount:(Inheritance)

  • The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
  • If there is a constructor present in the subclass, it needs to first call super() before using “this”.
  • This allows the child class to inherit all of the behavior of the parent class.
  • We can extend our parent class by building a child class to test out the functionality of extends.

Example:

Class Properties or getters and setters:

Getters:

  • The get syntax binds an object property to a function that will be called when that property is looked up.
  • Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls.

Syntax:

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

Setters:

  • In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed.
  • Setters are most often used in conjunction with getters to create a type of pseudo-property.
  • It is not possible to simultaneously have a setter on a property that holds an actual value.
  • A setter can be removed using the delete operator.

Syntax:

Example:

Arrays in ES6:

  • One of the most important features of any programming language are arrays, they  have several long-time requested feature updates in JavaScript ES6.
  • Arrays are generally described as “list-like objects”; they are basically single objects that contain multiple values stored in a list.
  • Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value.

Example:

Array Methods:

forEach():

  • ES6 introduced the Array.forEach() method for looping through arrays.
  • The forEach() method executes a provided function once for each array element.
  • forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized.
  • callback is invoked with three arguments:
    • the element value
    • the element index
    • the array being traversed

Syntax:

 


The forEach will loop through with all the elements in the array and also we can access the individual elements too.Example:

Filter():

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.
  • filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

Syntax:

Parameters:

  • callback − Function to test for each element.
  • thisObject − Object to use as this when executing callback.

Example:

  • uses filter() to create a filtered array that has all elements with values greater than 10000.

Find():

  • The Array.find() method returns the value of the first element in an array that passes a given test.
  • There are a few rules,
  • Test must be provided as a function.
  • find() method executes a callback function once for each element in the array until it finds a value that returns true.
  • If nothing passes, undefined is returned.
  • find() does not mutate or change the original Array.

Syntax:

Example:

Map():

The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.

  • Here, we transform our array from one array to another array.
  • Map is a data collection type  in which, data is stored in a form of pairs, which contains a unique key and value mapped to that key.
  • And because of the uniqueness of each stored key, there is no duplicate pair stored.
  • map() method creates a new array with the results of calling a provided function on every element in this array.

Syntax:

Parameters:

  • callback − Function that produces an element of the new Array from an element of    the current one.
  • thisObject − Object to use as this when executing callback.

Example:

Reduce():

  • The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
  • Just like .map(), .reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.
  • The accumulator can be pretty much anything and must be instantiated or passed when calling .reduce().

Syntax:

Example:

  • Here, we are displaying both the array and the squareArray. You can see the output of the squareArray as a single value.

Arrow functions:

  • Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope.
  • Arrow functions also called “fat arrow” functions, from CoffeeScript (a transcompiled language) are a more concise syntax for writing function expressions.
  • They utilize a new token =>, that looks like a fat arrow.
  • Arrow functions are anonymous and change the way this binds in functions.
  • Arrow functions make our code more concise, and simplify function scoping and the this keyword.
  • They are one-line mini functions which work much like Lambdas in other languages like C# or Python.
  • By using arrow functions, we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.

Syntax:

Here, we are using the previous example with arrow function.Example:

Modules:

  • A module is nothing more than a chunk of JavaScript code written in a file.
  • The functions or variables in a module are not available for use, unless the module file exports them.
  • In simpler terms, the modules help you to write the code in your module and expose only those parts of the code that should be accessed by other parts of your code.
  • ES6 modules will have to be transpiled to ES5 code so that we can run and test the code. Transpilation is the process of converting code from one language into its counterpart equivalent.
  • The ES6 Module Transpiler is a tool that takes your ES6 module and compiles it into ES5 compatible code in the CommonJS or AMD style.
  • ES6 modules is a very powerful concept. Although support is not available everywhere yet, you can play with ES6 code today and transpile into ES5.

Benefits of using modules:

  • Code can be split into smaller files of self-contained functionality.
  • The same modules can be shared across any number of applications.
  • Ideally, modules need never be examined by another developer, because they’ve has been proven to work.
  • Code referencing a module understands it’s a dependency. If the module file is changed or moved, the problem is immediately obvious.

Single page application: [SPA]

  • In complete application we will have only one html. Such applications are called as SPA.
  • Angular follows SPA. mean in any application developed with Angular is going to have only one html.
  • In typical asp.net applications we will have multiple html or aspx page where we redirect.
  • In Non SPA each time we will move from page to another page complete page life cycle is going to start again
  • Before ES6 All the JS Files Required by application are loaded into the HTML page on the page load it self.
  • If an app needs only login.js for the app to start , it still loads all other 10 js files like util,log,register,productlist,cart etc js files which are not required at start.

Disadvantages of above approach:

  • Makes the page load slow
  • Occupies browser memory

Modules in js [import and export]:

Export:

  • The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement.
  • Exported modules are in strict mode whether you declare them as such or not. The export statement cannot be used in embedded scripts.

syntax:

Import:

The import statement is used to import bindings which are exported by another module.

  • Imported modules are in strict mode whether you declare them as such or not. The import statement cannot be used in embedded scripts unless such script has a type=”module”.

syntax:

Import and export commands are the basics way to communicate between modules.

Example:

module.html

Logger.js

Matlib.js:

 

Util.js:

  • When you try to run this module.html file it will show the error as follows,
  • We need to run our application inside the web server instead of running it in a browser.
  • Go to the command prompt or node prompt, in the specified path start the http server by using the command,   Http-server.

Web Server:

  • The primary function of a web server is to store, process and deliver web pages to clients.
  • The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP).
  • Pages delivered are most frequently HTML documents, which may include images, style sheets and scripts in addition to the text content.
  • A web server is a system that delivers content or services to end users over the internet.
  • A web server consists of a physical server, server operating system (OS) and software used to facilitate HTTP communication.
  • A web server is also known as an internet server.

Various web servers:

  • IIS
  • TomCat
  • Apache
  • XAMP
  • Http-server (from nodejs)

ORIGIN:

  • The Origin request header indicates where a fetch originates from. It doesn’t include any path information, but only the server name.
  • It is sent with CORS requests, as well as with POST requests. It is similar to the Referer header, but, unlike this header, it doesn’t disclose the whole path.

Origin Server:

  • The purpose of an origin server is to process and respond to incoming Internet requests from Internet clients.
  • The concept of an origin server is typically used in conjunction with the concept of an edge server or caching server.
  • At its core, an origin server is a computer running one or more programs that are designed to listen for and process incoming Internet requests.
  • An origin server can take on all the responsibility of serving up the content for an Internet property such as a website, provided that the traffic does not extend beyond what the server is capable of processing and latency is not a primary concern.

Syntax:

<scheme>

  • The protocol that is used. Usually it is the HTTP protocol or its secured version, HTTPS.

<hostname>

  • The domain name of the server (for virtual hosting) or the IP.

<port> Optional

  • TCP port number on which the server is listening. If no port is given, the default port for the service requested (e.g., “80” for an HTTP URL) is implied.

Example:

  • http://192.168.0.20:8080
  • Http
  • Ip address
  • Port number

CORS:

  • Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
  • A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.
  • CORS allows web scripts to interact more openly with content outside of the original domain, leading to better integration between web services.
  • To prevent websites from tampering with each other, web browsers implement a security measure known as the same-origin policy.
  • The same-origin policy lets resources (such as JavaScript) interact with resources from the same domain, but not with resources from a different domain.
  • This provides security for the user by preventing abuse, such as running a script that reads the password field on a secure website.
  • In cases where cross-domain scripting is desired, CORS allows web developers to work around the same-origin policy.
  • CORS adds HTTP headers which instruct web browsers on how to use and manage cross-domain content.
  • The browser then allows or denies access to the content based on its security configuration.

Example:

  • Cross Origin Resource Sharing
  • Origin : http://icici:8765
  • Origin :  http://citi:8564

BUNDLING:

  • A web essentials bundle file is a recipe for grouping, and usually compressing, a set of files of the same type to limit the number and the amout the data to be downloaded by the browser.

Web Essentials offers two bundling types:

.bundle : for CSS and JS files.

  • For CSS, it outputs a XML bundle recipe file, a destination CSS file and a minified version of source if you turn on the minify option on the recipe.
  • For JavaScript files, it outputs a destination JS file, a minified version of sources and a source-map of that min.

.sprite : for images (PNG, JPG and GIF).

  • It generates a sprite image, CSS with example code for all the possible coordinates in background property, LESS and SASS files with mixins holding the same background properties and a custom map file (JSON) with all those coordinates.
  • LESS  and SASS  most popular CSS preprocessors.

Minification:

  • Minification is the process of minimizing code and markup in your web pages and script files.
  • It’s one of the main methods used to reduce load times and bandwidth usage on websites.
  • Minification dramatically improves site speed and accessibility, directly translating into a better user experience.
  • It’s also beneficial to users accessing your website through a limited data plan and who would like to save on their bandwidth usage while surfing the web.

Why minify HTML, CSS, and JavaScript ?

  • When creating HTML, CSS and JavaScript (JS) files, developers tend to use spacing, comments and well-named variables to make code and markup readable for themselves.
  • It also helps others who might later work on the assets. While this is a plus in the development phase, it becomes a negative when it comes to serving your pages.
  • Web servers and browsers can parse file content without comments and well-structured code, both of which create additional network traffic without providing any functional benefit.
  • To minify JS, CSS and HTML files, comments and extra spaces need to be removed, as well as crunch variable names so as to minimize code and reduce file size.
  • The minified file version provides the same functionality while reducing the bandwidth of network requests.
  • Minification has become standard practice for page optimization. All major JavaScript library developers (bootstrap, JQuery, AngularJS, etc.) provide minified versions of their files for production deployments, usually denoted with a min.js name extension.