1578619623
ECMAScript (ES) is a standardised scripting language for JavaScript (JS). The current ES version supported in modern browsers is ES5. However, ES6 tackles a lot of the limitations of the core language, making it easier for devs to code.
The most common and important standards that are being used in the software development industry are ES5 (also known as ECMAScript 2009) and ES6 (also known as ECMAScript 2015).
In this article, we will understand the different features of ES5 and ES6 versions of JavaScript. We will discuss problems that were found in ECMAScript 2009 and changes that have been made in ECMAScript 2015 to overcome the limitations of ES5 and further improve JavaScript language.
The const keyword of ES6 is used to declare the read only variables, whose values cannot be changed.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const pi = 3.14;
var r = 4;
console.log(pi * r * r); //output "50.24"
pi = 12;
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
It throws an Uncaught TypeError: Assignment to constant variable, because variables declared using const keyword cannot be modified.
The var Keyword
In ECMAScript 5 and earlier versions of JavaScript, the var statement is used to declare variables.
Here is an example that demonstrates how to create function-scoped variables:
<!DOCTYPE html>
<html>
<head>
<script>
var x = 11; // can be accessed globally
function myFunction()
{
console.log(x);
var y = 12; //can be accessed throughout function
if(true)
{
var z = 13; //can be accessed throughout function
console.log(y);
}
console.log(z);
}
myFunction();
</script>
</head>
<body></body>
</html>
Here, as you can see, the z variable is accessible outside the if statement, but that is not the case with other programming languages. Programmers coming from other language backgrounds would expect the z variable to be undefined outside the if statement, but that’s not the case. Therefore, ES6 had introduced the let keyword, which can be used for creating variables that are block scoped.
The let keyword
The let keyword is used for declaring block scoped variables. As earlier versions of JavaScript do not support block scoped variables, and nearly each and every programming language supports block scoped variables due to this limitation, the let keyword is introduced in ES6.
Variables declared using the let keyword are called block scoped variables. When the block scoped variables are declared inside a block, then they are accessible inside the block that they are defined in (and also any sub-blocks) but not outside the block.
<!DOCTYPE html>
<html>
<head>
<script>
let x = 13; //can be accessed globally
function myFunction()
{
console.log(x);
let y = 14; //can be accessed throughout function
if(true)
{
let z = 14; //cannot be accessed outside of the "if" statement
console.log(y);
}
console.log(z);
}
myFunction();
</script>
</head>
<body>
</body>
</html>
The above code throws Uncaught ReferenceError: z is not defined
Now, the output is as expected by a programmer who is used to another programming language. Here variables are declared using let keyword inside the {} block and cannot be accessed from outside.
In ECMAScript 5, JavaScript function is defined using function keyword followed by name and parentheses ().
Here is an example,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const add1 = function(a,b)
{
return a+b;
}
console.log(add1(60,20));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In ECMAScript 6, functions can be created using => operator. These functions with => operator are called arrow functions. With arrow functions, we can write shorter function syntax. If function is having only one statement and that statement is returning a value, then the brackets {} and return keyword can be removed from the function definition.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const add1 = (a,b) => a+b;
console.log(add1(50,20));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
Earlier versions of JavaScript did not have true object inheritance, they had prototype inheritance. Therefore ES6 has provided a feature called classes to help us organize our code in a better way and to make it more legible.
Object creation in ES5 version of JavaScript is as follows,
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function Car(options){
this.title = options.title;
}
Car.prototype.drive = function(){
return 'vroom';
};
function Toyota(options){
Car.call(this,options);
this.color = options.color;
}
Toyota.prototype = Object.create(Car.prototype);
ToyotaToyota.prototype.constructor = Toyota;
Toyota.prototype.honk = function(){
return 'beep';
}
const toyota = new Toyota({color:"red",title:"Daily Driver"});
document.getElementById("demo").innerHTML = toyota.drive();
document.getElementById("demo1").innerHTML = toyota.title;
document.getElementById("demo2").innerHTML = toyota.honk();
document.getElementById("demo3").innerHTML = toyota.color;
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
</body>
</html>
From the above code, we can see that constructor object creation and prototype inheritance is very complicated.
Therefore to organize our code in a better way and to make it much easier to read and understand, ES6 has provided a feature called class. We can use classes for setting up some level of inheritance as well as to create objects to make code more legible.
Declare a class using class keyword and add constructor() method to it.
<!DOCTYPE html>
<html>
<head>
<script>
class Car {
constructor(brand)
{
this.title=brand;
}
drive() {
return 'i have a '+this.title;
}
}
class Toyota extends Car{
constructor(brand,color){
super(brand);
this.color=color;
}
honk()
{
return this.drive()+',its a '+this.color;
}
}
const toyota = new Toyota("Ford","red");
document.getElementById("demo2").innerHTML = toyota.honk();
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>JavaScript Class</h2>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
</body>
</html>
Above code defines a class named ‘Car’ which is having its own constructor and method. Another class ‘Toyota’ is inheriting ‘Car’ constructor and method with the help of extends keyword.
While ECMAScript 5 introduced lots of methods in order to make arrays easier to use, ECMAScript 6 has added lot more functionality to improve array performance such as new methods for creating arrays and functionality to create typed arrays.
In ECMAScript 5 and earlier versions of JavaScript, there were two ways to create arrays such as creating arrays using array constructor and array literal syntax.
Creating arrays using array constructor,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let items = new Array(2);
console.log(items.length); // 2
console.log(items[0]); // undefined
console.log(items[1]); // undefined
items1 = new Array("2");
console.log(items1.length); // 1
console.log(items1[0]); // "2"
items2 = new Array(1, 2);
console.log(items2.length); // 2
console.log(items2[0]); // 1
console.log(items2[1]); // 2
items3 = new Array(3, "2");
console.log(items3.length); // 2
console.log(items3[0]); // 3
console.log(items3[1]);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
As we can see from the above example, on passing a single numerical value to the array constructor, the length property of that array is set to that value and it would be an empty array. On passing a single non-numeric value, the length property is set to one. If multiple values are being passed (whether numeric or not) to the array, those values become items in the array.
This behavior is confusing and risky, because we might not always be aware of the type of data being passed.
Solution provided in ECMAScript 6 version of JavaScript is as follows,
In order to solve the problem of a single argument being passed in an array constructor, ECMAScript 6 version of JavaScript introduced the Array.of() method.
The Array.of() method is similar to array constructor approach for creating arrays but unlike array constructor, it has no special case regarding single numerical value. No matter how many arguments are provided to the Array.of() method, it will always create an array of those arguments.
Here is an example showing the use of Array.of() method,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let items4 = Array.of(1, 2);
console.log(items4.length); // 2
console.log(items4[0]); // 1
console.log(items4[1]); // 2
items5 = Array.of(2);
console.log(items5.length); // 1
console.log(items5[0]); // 2
Items6 = Array.of("2");
console.log(items6.length); // 1
console.log(items6[0]); // "2"
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
Converting a non array object to an array has always been complicated, prior to ECMAScript 6 version of JavaScript. For instance, if we are having an arguments object and we want to use it like an array, then we have to convert it to an array first.
In ECMAScript 5 version of JavaScript, in order to convert an array like object to an array, we have to write a function like in the below code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function createArray(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
result.push(arr[i]);
}
return result;
}
var args = createArray("ABCDEFGHIJKL");
console.log(args);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
Even though this approach of converting an array like object to an array works fine, it is taking a lot of code to perform a simple task.
Therefore in order to reduce the amount of code, ECMAScript 6 version of JavaScript introduced Array.from() method. The Array.from() method creates a new array on the basis of items provided as arguments during function call.
For example let’s consider the following example
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var arg = Array.from("ABCDEFGHIJKLMNO");
console.log(arg);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In the above code, the Array.from() method creates an array from string provided as an argument.
Before ECMAScript 5, searching in an array was a complicated process because there were no built in functions provided to perform this task. Therefore ECMAScript 5 introduced indexOf() and lastIndexOf() methods to search for a particular value in an array.
The indexOf() method,
<!DOCTYPE html>
<html>
<head>
<script>
var languages = ["C#", "JavaScript", "Java", "Python"];
var x = languages.indexOf("Java");
console.log(x);
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
The lastIndexOf() methods,
<!DOCTYPE html>
<html>
<head>
<script>
var languages = ["C#", "JavaScript", "Java", "Python","C#"];
var x = languages.lastIndexOf("C#");
console.log(x);
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
These two methods work fine, but their functionality was still limited as they can search for only one value at a time and just return their position.
Suppose, we want to find the first even number in an array of numbers, then we have to write our own code as there are no inbuilt functions available to perform this task in the ECMAScript 5 version of JavaScript. The ECMAScript 6 version of JavaScript solved this problem by introducing find() and findIndex() methods.
The array.find() method returns the value of first array element which satisfies the given test (provided as a function). The find() method takes two arguments as follows:-
Array.find (function(value, index, array),thisValue).
The Array.findIndex() method is similar to the find() method. The findIndex() method returns the index of the satisfied array element.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let numbers = [25, 30, 35, 40, 45];
console.log(numbers.find(n => n % 2 ==0 ));
console.log(numbers.findIndex(n => n % 2 ==0));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In ES5, sets and maps objects can be created using Object.create() as follows,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var set = Object.create(null);
set.firstname = "Krysten";
set.lastname = "Calvin";
console.log(set.firstname);
console.log(set.lastname);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In this example, the object set is having a null prototype, to ensure that the object does not have any inherited properties.
Using objects as sets and maps works fine in simple situations. But this approach can cause problems, when we want to use strings and numbers as keys because all object properties are strings by default, therefore strings and numbers will be treated as same property, and two keys cannot evaluate the same string.
For example, let’s consider the following code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var map = Object.create(null);
map[2] = "hello";
console.log(map["2"]);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
In this example, the numeric key of 2 is assigned a string value “hello" as all object properties are strings by default. The numeric value 2 is converted to a string, therefore map[“2”] and map[2] actually reference the same property.
Sets
A set is an ordered list of elements that cannot contain duplicate values. Set object is created using new Set(), and items are added to a set by calling the add() method.
You can see how many items are in a set by checking the size property,
Lets consider the following code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let set = new Set();
set.add(10);
set.add(20);
set.add(30);
set.add(40);
console.log(set);
console.log(set.size);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
Here size property returns the number of elements in the Set. And add method adds the new element with a specified value at the end of the Set object.
Maps
A map is a collection of elements that contains elements as key, value pair. Each value can be retrieved by specifying the key for that value. The ECMAScript 6 Map type is an ordered list of key-value pairs, where the key and the value can be any type.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let map = new Map();
map.set("firstname", "Shan");
map.set("lastname", "Tavera");
console.log(map.get("firstname"));
console.log(map.get("lastname"));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
JavaScript functions have different functionalities in comparison to other programming languages such that any number of parameters are allowed to be passed in spite of the number of parameters declared in function definition. Therefore, functions can be defined that are allowed to handle any number of parameters just by passing in default values when there are no parameters provided.
Default parameters in ECMAScript 5
Now we are going to discuss, how function default parameters would be handled in ECMAScript 5 and earlier versions of ECMAScipt. JavaScript does not support the concept of default parameters in ECMAScript 5, but with the help of logical OR operator (||) inside function definition, the concept of default parameters can be applied.
To create functions with default parameters in ECMAScipt 5, the following syntax would be used,
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function calculate(a, b) {
aa = a || 30;
bb = b || 40;
console.log(a, b);
}
calculate(10,20); // 10 20
calculate(10); // 10 40
calculate(); // 30 40
</script>
</body>
</html>
Inside function definition, missing arguments are automatically set to undefined. We can use logical OR (||) operator in order to detect missing values and set default values. The OR operator looks for the first argument, if it is true, the operator returns it, and if not, the operator returns the second argument.
Default parameters in ECMAScript 6
ECMAScript 6, allows default parameter values to be put inside the function declaration. Here we are initializing default values inside function declaration which is used when parameters are not provided during function calling.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function calculate(a=30, b=40) {
console.log(a, b);
}
calculate(10,20); // 10 20
calculate(10); // 10 40
calculate(); // 30 40
</script>
</body>
</html>
In this article, we have discussed briefly, the differences between ES5 and ES6 versions of JavaScript as well as some of the new features introduced in each of these versions. Each and every feature has been explained with proper coding examples.
I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you so much!
#javascript #es6 #es5 #ECMAScript #difference
1578619623
ECMAScript (ES) is a standardised scripting language for JavaScript (JS). The current ES version supported in modern browsers is ES5. However, ES6 tackles a lot of the limitations of the core language, making it easier for devs to code.
The most common and important standards that are being used in the software development industry are ES5 (also known as ECMAScript 2009) and ES6 (also known as ECMAScript 2015).
In this article, we will understand the different features of ES5 and ES6 versions of JavaScript. We will discuss problems that were found in ECMAScript 2009 and changes that have been made in ECMAScript 2015 to overcome the limitations of ES5 and further improve JavaScript language.
The const keyword of ES6 is used to declare the read only variables, whose values cannot be changed.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const pi = 3.14;
var r = 4;
console.log(pi * r * r); //output "50.24"
pi = 12;
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
It throws an Uncaught TypeError: Assignment to constant variable, because variables declared using const keyword cannot be modified.
The var Keyword
In ECMAScript 5 and earlier versions of JavaScript, the var statement is used to declare variables.
Here is an example that demonstrates how to create function-scoped variables:
<!DOCTYPE html>
<html>
<head>
<script>
var x = 11; // can be accessed globally
function myFunction()
{
console.log(x);
var y = 12; //can be accessed throughout function
if(true)
{
var z = 13; //can be accessed throughout function
console.log(y);
}
console.log(z);
}
myFunction();
</script>
</head>
<body></body>
</html>
Here, as you can see, the z variable is accessible outside the if statement, but that is not the case with other programming languages. Programmers coming from other language backgrounds would expect the z variable to be undefined outside the if statement, but that’s not the case. Therefore, ES6 had introduced the let keyword, which can be used for creating variables that are block scoped.
The let keyword
The let keyword is used for declaring block scoped variables. As earlier versions of JavaScript do not support block scoped variables, and nearly each and every programming language supports block scoped variables due to this limitation, the let keyword is introduced in ES6.
Variables declared using the let keyword are called block scoped variables. When the block scoped variables are declared inside a block, then they are accessible inside the block that they are defined in (and also any sub-blocks) but not outside the block.
<!DOCTYPE html>
<html>
<head>
<script>
let x = 13; //can be accessed globally
function myFunction()
{
console.log(x);
let y = 14; //can be accessed throughout function
if(true)
{
let z = 14; //cannot be accessed outside of the "if" statement
console.log(y);
}
console.log(z);
}
myFunction();
</script>
</head>
<body>
</body>
</html>
The above code throws Uncaught ReferenceError: z is not defined
Now, the output is as expected by a programmer who is used to another programming language. Here variables are declared using let keyword inside the {} block and cannot be accessed from outside.
In ECMAScript 5, JavaScript function is defined using function keyword followed by name and parentheses ().
Here is an example,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const add1 = function(a,b)
{
return a+b;
}
console.log(add1(60,20));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In ECMAScript 6, functions can be created using => operator. These functions with => operator are called arrow functions. With arrow functions, we can write shorter function syntax. If function is having only one statement and that statement is returning a value, then the brackets {} and return keyword can be removed from the function definition.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
const add1 = (a,b) => a+b;
console.log(add1(50,20));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
Earlier versions of JavaScript did not have true object inheritance, they had prototype inheritance. Therefore ES6 has provided a feature called classes to help us organize our code in a better way and to make it more legible.
Object creation in ES5 version of JavaScript is as follows,
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function Car(options){
this.title = options.title;
}
Car.prototype.drive = function(){
return 'vroom';
};
function Toyota(options){
Car.call(this,options);
this.color = options.color;
}
Toyota.prototype = Object.create(Car.prototype);
ToyotaToyota.prototype.constructor = Toyota;
Toyota.prototype.honk = function(){
return 'beep';
}
const toyota = new Toyota({color:"red",title:"Daily Driver"});
document.getElementById("demo").innerHTML = toyota.drive();
document.getElementById("demo1").innerHTML = toyota.title;
document.getElementById("demo2").innerHTML = toyota.honk();
document.getElementById("demo3").innerHTML = toyota.color;
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
</body>
</html>
From the above code, we can see that constructor object creation and prototype inheritance is very complicated.
Therefore to organize our code in a better way and to make it much easier to read and understand, ES6 has provided a feature called class. We can use classes for setting up some level of inheritance as well as to create objects to make code more legible.
Declare a class using class keyword and add constructor() method to it.
<!DOCTYPE html>
<html>
<head>
<script>
class Car {
constructor(brand)
{
this.title=brand;
}
drive() {
return 'i have a '+this.title;
}
}
class Toyota extends Car{
constructor(brand,color){
super(brand);
this.color=color;
}
honk()
{
return this.drive()+',its a '+this.color;
}
}
const toyota = new Toyota("Ford","red");
document.getElementById("demo2").innerHTML = toyota.honk();
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>JavaScript Class</h2>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
</body>
</html>
Above code defines a class named ‘Car’ which is having its own constructor and method. Another class ‘Toyota’ is inheriting ‘Car’ constructor and method with the help of extends keyword.
While ECMAScript 5 introduced lots of methods in order to make arrays easier to use, ECMAScript 6 has added lot more functionality to improve array performance such as new methods for creating arrays and functionality to create typed arrays.
In ECMAScript 5 and earlier versions of JavaScript, there were two ways to create arrays such as creating arrays using array constructor and array literal syntax.
Creating arrays using array constructor,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let items = new Array(2);
console.log(items.length); // 2
console.log(items[0]); // undefined
console.log(items[1]); // undefined
items1 = new Array("2");
console.log(items1.length); // 1
console.log(items1[0]); // "2"
items2 = new Array(1, 2);
console.log(items2.length); // 2
console.log(items2[0]); // 1
console.log(items2[1]); // 2
items3 = new Array(3, "2");
console.log(items3.length); // 2
console.log(items3[0]); // 3
console.log(items3[1]);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
As we can see from the above example, on passing a single numerical value to the array constructor, the length property of that array is set to that value and it would be an empty array. On passing a single non-numeric value, the length property is set to one. If multiple values are being passed (whether numeric or not) to the array, those values become items in the array.
This behavior is confusing and risky, because we might not always be aware of the type of data being passed.
Solution provided in ECMAScript 6 version of JavaScript is as follows,
In order to solve the problem of a single argument being passed in an array constructor, ECMAScript 6 version of JavaScript introduced the Array.of() method.
The Array.of() method is similar to array constructor approach for creating arrays but unlike array constructor, it has no special case regarding single numerical value. No matter how many arguments are provided to the Array.of() method, it will always create an array of those arguments.
Here is an example showing the use of Array.of() method,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let items4 = Array.of(1, 2);
console.log(items4.length); // 2
console.log(items4[0]); // 1
console.log(items4[1]); // 2
items5 = Array.of(2);
console.log(items5.length); // 1
console.log(items5[0]); // 2
Items6 = Array.of("2");
console.log(items6.length); // 1
console.log(items6[0]); // "2"
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
Converting a non array object to an array has always been complicated, prior to ECMAScript 6 version of JavaScript. For instance, if we are having an arguments object and we want to use it like an array, then we have to convert it to an array first.
In ECMAScript 5 version of JavaScript, in order to convert an array like object to an array, we have to write a function like in the below code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function createArray(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
result.push(arr[i]);
}
return result;
}
var args = createArray("ABCDEFGHIJKL");
console.log(args);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
Even though this approach of converting an array like object to an array works fine, it is taking a lot of code to perform a simple task.
Therefore in order to reduce the amount of code, ECMAScript 6 version of JavaScript introduced Array.from() method. The Array.from() method creates a new array on the basis of items provided as arguments during function call.
For example let’s consider the following example
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var arg = Array.from("ABCDEFGHIJKLMNO");
console.log(arg);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In the above code, the Array.from() method creates an array from string provided as an argument.
Before ECMAScript 5, searching in an array was a complicated process because there were no built in functions provided to perform this task. Therefore ECMAScript 5 introduced indexOf() and lastIndexOf() methods to search for a particular value in an array.
The indexOf() method,
<!DOCTYPE html>
<html>
<head>
<script>
var languages = ["C#", "JavaScript", "Java", "Python"];
var x = languages.indexOf("Java");
console.log(x);
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
The lastIndexOf() methods,
<!DOCTYPE html>
<html>
<head>
<script>
var languages = ["C#", "JavaScript", "Java", "Python","C#"];
var x = languages.lastIndexOf("C#");
console.log(x);
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
These two methods work fine, but their functionality was still limited as they can search for only one value at a time and just return their position.
Suppose, we want to find the first even number in an array of numbers, then we have to write our own code as there are no inbuilt functions available to perform this task in the ECMAScript 5 version of JavaScript. The ECMAScript 6 version of JavaScript solved this problem by introducing find() and findIndex() methods.
The array.find() method returns the value of first array element which satisfies the given test (provided as a function). The find() method takes two arguments as follows:-
Array.find (function(value, index, array),thisValue).
The Array.findIndex() method is similar to the find() method. The findIndex() method returns the index of the satisfied array element.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let numbers = [25, 30, 35, 40, 45];
console.log(numbers.find(n => n % 2 ==0 ));
console.log(numbers.findIndex(n => n % 2 ==0));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In ES5, sets and maps objects can be created using Object.create() as follows,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var set = Object.create(null);
set.firstname = "Krysten";
set.lastname = "Calvin";
console.log(set.firstname);
console.log(set.lastname);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
In this example, the object set is having a null prototype, to ensure that the object does not have any inherited properties.
Using objects as sets and maps works fine in simple situations. But this approach can cause problems, when we want to use strings and numbers as keys because all object properties are strings by default, therefore strings and numbers will be treated as same property, and two keys cannot evaluate the same string.
For example, let’s consider the following code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var map = Object.create(null);
map[2] = "hello";
console.log(map["2"]);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
In this example, the numeric key of 2 is assigned a string value “hello" as all object properties are strings by default. The numeric value 2 is converted to a string, therefore map[“2”] and map[2] actually reference the same property.
Sets
A set is an ordered list of elements that cannot contain duplicate values. Set object is created using new Set(), and items are added to a set by calling the add() method.
You can see how many items are in a set by checking the size property,
Lets consider the following code,
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let set = new Set();
set.add(10);
set.add(20);
set.add(30);
set.add(40);
console.log(set);
console.log(set.size);
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
Here size property returns the number of elements in the Set. And add method adds the new element with a specified value at the end of the Set object.
Maps
A map is a collection of elements that contains elements as key, value pair. Each value can be retrieved by specifying the key for that value. The ECMAScript 6 Map type is an ordered list of key-value pairs, where the key and the value can be any type.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
let map = new Map();
map.set("firstname", "Shan");
map.set("lastname", "Tavera");
console.log(map.get("firstname"));
console.log(map.get("lastname"));
</script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
</html>
JavaScript functions have different functionalities in comparison to other programming languages such that any number of parameters are allowed to be passed in spite of the number of parameters declared in function definition. Therefore, functions can be defined that are allowed to handle any number of parameters just by passing in default values when there are no parameters provided.
Default parameters in ECMAScript 5
Now we are going to discuss, how function default parameters would be handled in ECMAScript 5 and earlier versions of ECMAScipt. JavaScript does not support the concept of default parameters in ECMAScript 5, but with the help of logical OR operator (||) inside function definition, the concept of default parameters can be applied.
To create functions with default parameters in ECMAScipt 5, the following syntax would be used,
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function calculate(a, b) {
aa = a || 30;
bb = b || 40;
console.log(a, b);
}
calculate(10,20); // 10 20
calculate(10); // 10 40
calculate(); // 30 40
</script>
</body>
</html>
Inside function definition, missing arguments are automatically set to undefined. We can use logical OR (||) operator in order to detect missing values and set default values. The OR operator looks for the first argument, if it is true, the operator returns it, and if not, the operator returns the second argument.
Default parameters in ECMAScript 6
ECMAScript 6, allows default parameter values to be put inside the function declaration. Here we are initializing default values inside function declaration which is used when parameters are not provided during function calling.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function calculate(a=30, b=40) {
console.log(a, b);
}
calculate(10,20); // 10 20
calculate(10); // 10 40
calculate(); // 30 40
</script>
</body>
</html>
In this article, we have discussed briefly, the differences between ES5 and ES6 versions of JavaScript as well as some of the new features introduced in each of these versions. Each and every feature has been explained with proper coding examples.
I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you so much!
#javascript #es6 #es5 #ECMAScript #difference
1594263503
Consider a simple scenario where you have an array of numbers and you want to return the sum of all elements in that array.
We will see that it’s a solution in ES5 and that it’s equivalent in ES6 to using reduce helper.
ES5 Code
The above code will return an output of 150.
ES6-Equivalent Code Using Reduce
The above code will also return output as 150.
You can write the same code in ES6 using Reduce Helper with arrow function as follows, which will return the same output.
#es6 #es5 code #es6-equivalent code
1649373360
gulp-es6-transpiler
Transpile ES6 to ES5 with es6-transpiler
Issues with the output should be reported on the es6-transpiler issue tracker.
$ npm install --save-dev gulp-es6-transpiler
var gulp = require('gulp');
var es6transpiler = require('gulp-es6-transpiler');
gulp.task('default', function () {
return gulp.src('src/app.js')
.pipe(es6transpiler())
.pipe(gulp.dest('dist'));
});
Use the es6-transpiler options, except for filename
, src
, outputToConsole
, outputFilename
.
Author: Sindresorhus
Source Code: https://github.com/sindresorhus/gulp-es6-transpiler
License: MIT License
1584513825
Arrow functions – a new feature introduced in ES6 – enable writing concise functions in JavaScript. While both regular and arrow functions work in a similar manner, yet there are certain interesting differences between them.
By using function a developer can easily create a block of codes. JavaScript also provides us with the facility to create functions. Due to the ES5 and ES6 standard of JavaScript, functions are also described in a different syntax. ES6 has introduced a new arrow based syntax to write a function which is also called fat arrow function. Let’s find the difference between the regular function and fat arrow function.
Without using any parameter:
/***** ES5 Regular Function *****/
let prtLangReg = function () {
console.log("JavaScript");
}
prtLangReg();
/***** ES6 Arrow Function *****/
let prtLangArrow = _ => {console.log("JavaScript");}
prtLangArrow();
With one parameter:
/***** ES5 Regular Function *****/
let prtLangReg = function (language) {
console.log(language);
}
prtLangReg("JavaScript");
/***** ES6 Arrow Function *****/
let prtLangArrow = (language) => { console.log(language); }
prtLangArrow("JavaScript");
With multiple parameters:
/***** ES5 Regular Function *****/
let prtLangReg = function (id, language) {
console.log(id + ".) " + language);
}
prtLangReg(1, "JavaScript");
/***** ES6 Arrow Function *****/
let prtLangArrow = (id, language) => { console.log(id + ".) " + language); }
prtLangArrow(1, "JavaScript");
As you have checked the basic function declaration using both ES5 and ES6. The syntax looks nearly the same but ES6 arrow function has much cleaner and precise syntax.
“this” is the keyword in JavaScript which has very importance it contains the reference. Reference may be window object or any other custom object depends on the condition.
let language = {
name: "JavaScript",
prtLangReg: function (id, language) {
console.log(this);
},
prtLangArrow: (id, language) => { console.log(this); }
}
language.prtLangReg(); // ES5 Function Call
language.prtLangArrow(); // ES6 Function Call
Copy/paste above code and check the result in the console. You will find regular function returns a reference to the current JavaScript Object and arrow function returns the reference to the global window object. Why an arrow function returns the global object? Arrow function gets “this” keyword scope from the parent or scope from the nearest regular function in which arrow function is defined.
let language = {
name: "JavaScript",
prtLangReg: function (id, language) {
console.log(this);
},
arrowUsingRegular: function () {
return (id, language) => {
console.log(this); // this refers to language Object
}
}
}
language.prtLangReg();
language.arrowUsingRegular()();
ES6 in JavaScript provides us with the arguments Object from which we can select all the parameters passed to the function. But Arrow function does not contain the argument object.
let language = {
name: "JavaScript",
prtLangReg: function () {
console.log(arguments); // 1, JavaScript
},
prtLangArrow: () => {
console.log(arguments); //argument is not defined
}
}
language.prtLangReg(1, "JavaScript");
language.prtLangArrow(1, "JavaScript");
Regular functions are working well with objects using the new keyword. They have the constructor function by which values can be initialized during object creation. It can be managed using the prototype chaining.
let Language = function (name) {
this.name = name;
}
Language.prototype.prtLangReg = function () {
console.log(this.name);
}
let language = new Language("JavaScript");
language.prtLangReg();
But arrow function does not have constructor function, prototype chaining. They are not working well with objects. They can not be used with the new keyword for assigning memory.
After checking the features of ES5 Regular and ES6 Arrow function now the question is what to choose for function declaration?
Arrow function performs well in Callbacks function like setTimeout, Map, Reduce etc. But Regular function performs well with Objects.
Do not use an arrow function with the objects. Always used with Higher-Order Function. Choose regular function when you have to work with the objects. Apart from that, arrow function has many other syntax related benefits like implicitly return values, shorter syntax. You can test those syntaxes as well.
Happy Coding!
#javascript #es6 #es5
1590736602
In this Modern JavaScript video we are going to learn about the [ ES6, ES7, ES8 ] features. and this course is about 2 Hours Crash Course. ECMAScript is a scripting-language specification standardized by Ecma International. It was created to standardize JavaScript to help foster multiple independent implementations. ES6 refers to version 6 of the ECMA Script programming language. It is a major enhancement to the JavaScript language, and adds many more features intended to make large-scale software development easier. in ES6 we have different features , especially in Object Oriented Programming.
Check our website:
https://www.codeloop.org
0 - Introduction = 00:00:04
1 - Let & Const(ES6) = 00:02:17
2 - Template Literals(ES6) = 00:08:54
3 - Rest Operator(ES6) = 00:12:41
4 - Spread Operator(ES6) = 00:15:31
5 - Default Parametrs(ES6) = 00:20:00
6 - For Of Loop(ES6) = 00:24:53
7 - Symbols(ES6) = 00:28:07
8 - Arrow Functions(ES6) = 00:31:32
9 - Multiline Arrow Function(ES6) = 00:37:40
10 - Default Param in Arrow Function = 00:41:14
11 - Object Destructuring(ES6) = 00:44:39
12 - Array Destructuring(ES6) = 00:48:29
13 - Sets And Maps(ES6) = 50:38
14 - Classes & Methods(ES6) = 01:00:28
15 - Static Function(ES6) = 01:06:15
16 - Getters & Setters(ES6) = 01:08:49
17 - Inheritance(ES6) = 01:11:15
18 - Exponentiation Oper(ES7) = 01:14:48
19 - Promises (ES6) = 01:16:05
20 - Includes() Function(ES7) = 01:35:29
21 - PadStart() & PadEnd() Function(ES8) = 01:37:46
22 - Object.Entries(ES8) = 01:40:45
23 - Object.Values(ES8) = 01:42:51
24 - Trailing Commas(ES8) = 01:44:19
25 - Asyn & Await (ES8) = 01:46:11
#javascript #modernjavascript #es6 #es5 #es7